首页 > java swing布局嵌套

java swing布局嵌套

小菜一枚,刚接触Java,想写个注册界面,但却遇到一个奇怪问题:代码如下:

public void frame()
    {
        this.frame = new JFrame("用户注册");
        
        //窗体基本属性
        this.frame.setSize(600, 400);
        this.frame.setLocationRelativeTo(null);
        this.frame.setVisible(true);
        this.frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
        //设置主面板,相当于外层div
        JPanel jp = new JPanel(new BorderLayout());
        
        //东西南北中,面板
        JPanel jp1 = new JPanel(new FlowLayout());
        JPanel jp2 = new JPanel(new FlowLayout());
        JPanel jp3 = new JPanel(new GridLayout(10,2));
        JPanel jp4 = new JPanel(new FlowLayout());
        JPanel jp5 = new JPanel(new FlowLayout());
        
        //加入主面板
        jp.add(BorderLayout.NORTH,jp1);
        jp.add(BorderLayout.SOUTH,jp2);
        jp.add(BorderLayout.CENTER,jp3);
        jp.add(BorderLayout.EAST,jp4);
        jp.add(BorderLayout.WEST,jp5);
        
    
        //标题
        JLabel jl1 = new JLabel("用户注册",SwingConstants.CENTER);
        jp1.add(jl1);
        
        //中间面板
        JButton jb2= new JButton("Btn");
        JTextField jt = new JTextField("usrname");
        JButton jb1 = new JButton("abc");    
        
        jp3.add(jt);
        jp3.add(jb1);
        jp3.add(jb2);
        
                
        this.container = this.frame.getContentPane();
        this.container.setBackground(Color.white);
        this.container.add(jp);

    }

主要思路:
一个主Jpanel,边界布局
5个子Panel,东西南北中
最后将主Panel加入Container中,但最后执行结果,Frame显示却是空白,如图:

新手,老鸟请教,谢谢!


因为你什么都没有往 JFrame 中添加就让它显示了,所以你应该把下面这段代码放到 frame() 方法的最后面:

//窗体基本属性
this.frame.setSize(600, 400);
this.frame.setLocationRelativeTo(null);
this.frame.setVisible(true);
this.frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

如果是使用ecilipse可以使用一个插件来实现可视化的布局设置(具体插件名忘记了)

【热门文章】
【热门文章】