Java Basic Gui示例

Nic*_*ris 1 java layout swing jbutton layout-manager

我是Java的GUIS的新手,我正在尝试创建一个类似我附加的图像的GUI,但是有多个JLabel和JTextFields.我想将按钮放在屏幕底部的中央.

我该怎么做呢?请忽略黑线,因为我找不到更好的图像.

在此输入图像描述

Mad*_*mer 6

您可以通过多种方式实现这一目标.对我来说,最简单的方法是使用GridBagLayout它,它是所有内置布局管理器中最灵活的,它也是最复杂的一个:P

很多人都抓住了一件事,就是试图在一个容器上布局组件.这可以做到,但需要花费大量时间和调整才能做到正确.

更好的方法(恕我直言)是使用多个子容器.

这允许您根据个人需要细分布局要求,并担心这些容器之间的关系是一个单独的问题.

例如,在您的问题中,您要求将单词和文本字段对齐在一起,但是它们被锚定到容器的北部位置,而按钮应该在南部,但是在标签和字段之间居中.

担心如何首先布局标签和字段,然后担心这些按钮和字段/标签之间的关系第二...

在此输入图像描述

public class TestLayout08 {

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

    public TestLayout08() {
        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();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new LayoutPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    protected  class LayoutPane extends JPanel {

        public LayoutPane() {
            JButton button = new JButton("Find Word");
            JLabel label = new JLabel("Word:");
            JTextField field = new JTextField(12);

            setLayout(new GridBagLayout());

            JPanel fieldPane = new JPanel(new GridBagLayout());

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.insets = new Insets(2, 2, 2, 2);

            fieldPane.add(label, gbc);
            gbc.gridx++;
            fieldPane.add(field, gbc);

            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.NORTH;
            gbc.weighty = 1;
            add(fieldPane, gbc);

            gbc.gridx = 0;
            gbc.gridy++;
            gbc.weighty = 0;
            gbc.anchor = GridBagConstraints.CENTER;

            add(button, gbc);    
        }        
    }
}
Run Code Online (Sandbox Code Playgroud)

看一眼;