我最近在书上看了java的3种布局管理器类:总结下来是:
1、border layout manger 可以把面板分成*行*列
2、flow layout manger   默认的布局管理器,组件添加上去一行空间不够会显示到下一行
3、gridbag layout manger 这个比较复杂,可以对每个组件的效果进行设置和约束另外还有一个类我一直弄不清,JPanel 类 ,。
我把JFrame类看成是框架,JPanel类看成是容器。就跟房子的框架和墙一样。
但是我今天看到个列子,程序中没有定义JPanel类,而直接使用JFrame.
这样做程序怎么可行?还有大家写项目的时候用哪一类的布局管理器,给些编写java表陈框架建议给我,谢谢。上面说的错误也请大家指正!

解决方案 »

  1.   

    1.JFrame和JPanel是不一样的两个类,JFrame继承自Window,而JPanel继承自Container,在Swing中Frame可以单独显示,在Frame里可以添加像按钮,Panel这样的组件和容器,而Panel必需依赖于Frame或Applet才能显示出界面,所以说Frame不需依赖于其他容器就能够显示出来,Swing中我们也经常继承这个类来显示界面
    2.常见的5种布局,基本上就用FlowLayout BorderLayout GridLayout 这三种
      

  2.   

    既然JFrame也可以装组件,我把下面代码中的JPanel容器去掉,为什么运行结果就不正确(能编译,能运行),代码作用是点击按钮把背景颜色变黄,我把代码贴出来:
    import java.awt.*;
    import java.lang.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ButtonTest
    {
    public static void main(String[] args){
    ButtonFrame frame=new ButtonFrame();
    frame.setVisible(true);
    }
    }class ButtonFrame extends JFrame
    {
    public ButtonFrame(){
    setTitle("ButtonTest");
    setSize(300,200); //Create Button
    JButton yellowButton=new JButton("yellow");
    buttonpanel=new JPanel();
    //add to Frame
    add(buttonpanel);
    buttonpanel.add(yellowButton);
    ColorAction yellowAction=new ColorAction(Color.YELLOW);
    yellowButton.addActionListener(yellowAction);
    }
    private class ColorAction implements ActionListener
    {
    public ColorAction(Color c){
    backgroundColor=c;
    } public void actionPerformed(ActionEvent event)
    {

    buttonpanel.setBackground(backgroundColor);
    }  private Color backgroundColor;
    }
    private JPanel buttonpanel;
    }
    我把Button组件直接添加到Frame中不经过JPanel后就得不到正确结果,求解释!!!