Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 网格布局组件';他的位置不起作用_Java_Swing_Gridbaglayout - Fatal编程技术网

Java 网格布局组件';他的位置不起作用

Java 网格布局组件';他的位置不起作用,java,swing,gridbaglayout,Java,Swing,Gridbaglayout,大家好,我是java初学者,使用GridBagLayout做小型GUI。请参阅所附代码和输出。我想要的是根据在gridx和gridy中指定的位置将JButtons放置在左上角。但它将组件放置在中间,而不是预期的左上角,如果我使用插图,gridx/gridy,所有这些都在工作,但不是从正确的坐标,所以请参阅附加的代码和图像,并指导我 public rect() { JPanel panel = new JPanel( new GridBagLayout());

大家好,我是java初学者,使用GridBagLayout做小型GUI。请参阅所附代码和输出。我想要的是根据在gridx和gridy中指定的位置将JButtons放置在左上角。但它将组件放置在中间,而不是预期的左上角,如果我使用插图,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); 


}
输出:想要左上角的这些按钮,请引导我


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


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

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);
        }
    });
}