【问题标题】:How to position components with GridBagLayout?如何使用 GridBagLayout 定位组件?
【发布时间】:2012-10-13 07:04:45
【问题描述】:

我是 Java 编程的新手,我正在尝试制作一个包含两个按钮和一个文本区域的窗口,如下图所示。 我遇到的问题是定位组件。我尝试使用 GridLayout 并将窗口分成 9 行和 16 个单元格,但后来发现我不能让组件占据超过一个单元格。我知道我应该使用GridBagLayout,但我不知道具体如何。帮助将不胜感激。 :)

【问题讨论】:

  • 所有 JComponent 都可以通过容器调整大小,或者不可以,例如

标签: java swing user-interface layout gridbaglayout


【解决方案1】:

您有多种选择。与其尝试将整个组件布局在一个整体中,不如尝试使用复合布局,将 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);                
        }            
    }        
}

【讨论】:

    猜你喜欢
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-03-15
    • 2022-01-08
    • 2014-06-26
    • 2018-07-30
    • 1970-01-01
    相关资源
    最近更新 更多