如何使用GridBagLayout定位组件?

6

我对Java编程还很陌生,正在尝试制作一个包含两个按钮和文本区域的窗口,如下图所示。 但是遇到了组件定位的问题。我尝试使用GridLayout并将窗口分成9行16列,但发现无法使组件占用多个单元格。我知道应该使用GridBagLayout,但不知道具体怎么做。希望能得到帮助。:)


所有的J组件都可以被容器调整大小,或者不可以。 - mKorbel
1个回答

7
你有很多选择。不要试图在一个布局中排列整个组件,而是尝试使用复合布局,在其中将UI的各个部分分别布局到不同的窗格中,并关注每个部分的单独需求...
public class TestLayout11 {

    public static void main(String[] args) {
        new TestLayout11();
    }

    public TestLayout11() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new ExamplePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    protected class ExamplePane extends JPanel {

        public ExamplePane() {
            setLayout(new GridBagLayout());

            JPanel buttonPane = new JPanel(new GridBagLayout());

            JButton btnOkay = new JButton("Ok");
            JButton btnCancel = new JButton("Cancel");

            JTextArea textArea = new JTextArea(5, 20);

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.anchor = GridBagConstraints.CENTER;
            buttonPane.add(btnOkay, gbc);
            gbc.gridy++;
            gbc.insets = new Insets(50, 0, 0, 0);
            buttonPane.add(btnCancel, gbc);

            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.insets = new Insets(100, 100, 100, 100);
            add(buttonPane, gbc);

            gbc.insets = new Insets(150, 100, 150, 100);
            gbc.gridx++;
            gbc.gridy = 0;
            gbc.fill = GridBagConstraints.BOTH;
            add(new JScrollPane(textArea), gbc);                
        }            
    }        
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接