首页 > 解决方案 > 如何在 java GUI swing 中设置布局?

问题描述

我正在尝试为我的应用程序(学校项目)创建一个注册表单,我想将布局设置为BoxLayoutJtextfields组合框有问题,如下所示,这个问题是否与setSize()我做的不正确有关,我只想要Jtextfields垂直排序,感谢支持 在此处输入图像描述

private JPanel SetUpRegister() {
        JLabel registerLabel = new JLabel("Registera");

        registerLabel.setFont(new Font("Arial", Font.BOLD, 30));
        loginRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
        passwordRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
        fnRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
        lnRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
        ageRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
        String[] genderlist = new String[] { "Male", "Female", "Other" };
        JComboBox<String> registerList = new JComboBox<>(genderlist);

        JPanel registerPanel = new JPanel();    
        registerPanel.setBackground(new Color(255, 140, 0));
        registerPanel.add(registerLabel);
        registerPanel.add(loginRegisterInput);
        registerPanel.add(passwordRegisterInput);
        registerPanel.add(fnRegisterInput);
        registerPanel.add(lnRegisterInput);
        registerPanel.add(ageRegisterInput);
        registerPanel.add(registerList);
        registerPanel.setLayout(new BoxLayout(registerPanel,BoxLayout.Y_AXIS));

        return registerPanel;

}

标签: javaswinguser-interfacelayout-managerboxlayout

解决方案


输入字段很大

BoxLayout当面板上有额外空间可用时,将尝试调整组件的大小。它会将组件的大小调整为最大大小。

由于某种原因, a 的最大高度对我JTextField来说Integer.MAX_VALUE毫无意义,因为当您输入更多文本时,文本的高度永远不会改变。

无论如何,您有几个选择:

  1. 使用不同的布局管理器,例如GridBagLayout. ,GridBagLayout将尊重文本字段的首选大小。
  2. 创建自定义JTestField并覆盖该getMaximumSize()方法以返回组件的首选高度
  3. 使用包装面板。

对于包装面板,您可以执行以下操作:

JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add(registerPanel, BorderLayout.PAGE_START);
return wrapper;
//return registerPanel;

BorderLayout 将尊重添加到 PAGE_START 的任何组件的首选高度,因此不需要 BoxLayout 调整任何组件的大小。


推荐阅读