java - 如何在 java GUI swing 中设置布局?
问题描述
我正在尝试为我的应用程序(学校项目)创建一个注册表单,我想将布局设置为BoxLayout
但Jtextfields
组合框有问题,如下所示,这个问题是否与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;
}
解决方案
输入字段很大
BoxLayout
当面板上有额外空间可用时,将尝试调整组件的大小。它会将组件的大小调整为最大大小。
由于某种原因, a 的最大高度对我JTextField
来说Integer.MAX_VALUE
毫无意义,因为当您输入更多文本时,文本的高度永远不会改变。
无论如何,您有几个选择:
- 使用不同的布局管理器,例如
GridBagLayout
. ,GridBagLayout
将尊重文本字段的首选大小。 - 创建自定义
JTestField
并覆盖该getMaximumSize()
方法以返回组件的首选高度 - 使用包装面板。
对于包装面板,您可以执行以下操作:
JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add(registerPanel, BorderLayout.PAGE_START);
return wrapper;
//return registerPanel;
BorderLayout 将尊重添加到 PAGE_START 的任何组件的首选高度,因此不需要 BoxLayout 调整任何组件的大小。
推荐阅读
- python-3.x - Rdkit:MaeMolSupplier NameError
- amazon-ec2 - Certbot Amazon Linux 错误无法生成 ssl 证书
- yaml - 定义警报 Prometheus 的缺失
- arangodb - 使用长度条件删除 Arango DB UI 中的记录
- .net - 实体框架核心迁移'数据库中已经有一个名为'TableName'的对象'
- r - ggtern 禁用 ggplot2 中的一些主题 - 仍然?
- android - 未调用 Android 导航 onNavigationItemSelected
- python - 将表从 ScrapySplash Lua 脚本传递到 Python
- c - 在 C 中使用 for 循环循环开关
- javascript - 如何从 SVG 文件制作可点击的地图?