首页 文章

GridBagLayout组件的位置不起作用

提问于
浏览
1

嗨,我是java的初学者,使用GridBagLayout做小GUI . 请参阅附加的代码以及输出 . 我想要的是按照gridx和gridy中指定的位置将JButtons放在左上角 . 但是如果我使用Insets,gridx / gridy所有工作但不是从正确的坐标,它将组件放置在中心而不是左上方,所以请查看附加的代码和图像并指导我

public  rect()
{     

      JPanel panel = new JPanel( new GridBagLayout());
      GridBagConstraints gbc = new GridBagConstraints();
      JButton nb1= new JButton("Button1  ");
      JButton nb2= new JButton("Button2  ");

      gbc.gridx=0;
      gbc.gridy=0 ;
      panel.add(nb1, gbc);
      gbc.gridx=1;
      gbc.gridy=1; 
      panel.add(nb2, gbc);
      panel.setVisible(true);
      JFrame  frame = new JFrame("Address Book "); 
      frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      frame.setSize(300, 300 );
      frame.add(panel);

      frame.setVisible(true); 


}

OUTPUT :想要左上角的这些按钮请指导我

enter image description here

1 回答

  • 1

    我认为问题更多的是使用 setSize(..) ,你应该在_24544800_实例上使用适当的 LayoutManager 并调用pack()后将所有组件添加到 JFrame 并且在设置 JFrame 可见之前,也不需要 panel.setVisible(..)

    enter image description here

    public static void main(String[] args) {
    
        SwingUtilities.invokeLater(new Runnable() {
            @Override
    
            public void run() {
                JPanel panel = new JPanel(new GridBagLayout());
    
                JButton nb1 = new JButton("Button1  ");
                JButton nb2 = new JButton("Button2  ");
    
                GridBagConstraints gbc = new GridBagConstraints();
    
                gbc.gridx = 0;
                gbc.gridy = 0;
                panel.add(nb1, gbc);
    
                gbc.gridx = 1;
                gbc.gridy = 1;
                panel.add(nb2, gbc);
    
                JFrame frame = new JFrame("Address Book ");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
                frame.add(panel);
    
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
    

相关问题