我对 Java Swing 非常陌生,在获得良好的布局方面遇到了很多问题。我已经查看了谷歌,甚至该网站上的其他答案,但我发现没有任何信息似乎可以解决该问题。这是我努力的结果:
正如您所看到的,标签、文本字段和按钮都没有对齐。我的目标是让它们都具有相同的左边框,按钮和文本字段具有相同的右边框,这些左边框和右边框与左边框和右边框的距离相同我的窗户两侧。
以下是我的代码的重要部分:
public void run()
{
JFrame frame = new JFrame("Arduino Server");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
InstancePanel = new ServerGUIPanel();
frame.getContentPane().add(InstancePanel);
frame.pack();
frame.setVisible(true);
}
并且,在 ServerGUIPanel.java 中:
public ServerGUIPanel()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setPreferredSize(new Dimension(500, 500));
setBorder(new EmptyBorder(10, 10, 10, 10));
StatusLabel = new JLabel("STATUS: BOOTUP");
add(StatusLabel);
PortField = new JTextField();
PortField.setPreferredSize(new Dimension(5000, 20));
PortField.setMaximumSize(PortField.getPreferredSize());
PortField.setActionCommand("PortChanged");
add(PortField);
ConnectionButton = new JButton();
ConnectionButton.setPreferredSize(new Dimension(5000, 20));
ConnectionButton.setMaximumSize(ConnectionButton.getPreferredSize());
ConnectionButton.setActionCommand("ConnectionClicked");
add(ConnectionButton);
}
有人对此有一个简单的解决方案吗?我在这里做错了什么?
非常感谢!
——乔治·奥茨·拉森
阅读 Swing 教程中的部分如何使用 BoxLayout有关使用 BoxLayout 的基础知识以及有关对齐问题的部分。
基本上,您需要确保所有组件的alignmentX值设置为左对齐。
Also:
- 不要使用 setPreferredSize() 来设置组件的大小。每个 Swing 组件都会确定其自己的首选大小。
- 使用 Java 命名约定。变量名称不应以大写字符开头。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)