Starting GridBagLayout from top left corner in Java Swing

后端 未结 6 650
执念已碎
执念已碎 2021-02-13 18:39

I\'m new to Java Swing and I have been struggling to start the GridBagLayout from top left corner so that c.gridx=0 c.gridy=0 will put my object on the top left corner.

6条回答
  •  遥遥无期
    2021-02-13 19:09

    There's a workaround. You can put the GridBagLayout panel in a BorderLayout panel with BorderLayout.NORTH. Then Component in GridBagLayout panel will start from top position.

    static void test4(){
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(480, 360);
    
        JPanel borderLayoutPanel=new JPanel(new BorderLayout());
        JPanel gridBagLayoutPanel = new JPanel(new GridBagLayout());
        borderLayoutPanel.add(gridBagLayoutPanel, BorderLayout.NORTH);
        frame.add(borderLayoutPanel);
    
        JButton testButton=new JButton("test button");
        GridBagConstraints c = new GridBagConstraints();
        c.gridx=0;
        c.gridy=0;
        gridBagLayoutPanel.add(testButton, c);
    
        frame.setVisible(true);
    }
    

提交回复
热议问题