我对 Java Swing 非常陌生,在获得良好的布局方面遇到了很多问题。我已经查看了谷歌,甚至该网站上的其他答案,但我发现没有任何信息似乎可以解决该问题。这是我努力的结果:
如您所见,标签、文本字段和按钮均未对齐。我的目标是让它们都具有相同的左边框,并且按钮和文本字段具有相同的右边框,这些左边框和右边框与左边框和右边框的距离相同我的 window 两侧。
以下是我的代码的重要部分:
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 教程中关于 How to Use BoxLayout 的部分了解使用 BoxLayout 的基础知识以及有关对齐问题的部分。
基本上,您需要确保所有组件的alignmentX值设置为左对齐。
另外:
- 不要使用 setPreferredSize() 来设置组件的大小。每个 Swing 组件都会确定其自己的首选大小。
- 使用 Java 命名约定。变量名称不应以大写字符开头。
关于Java Swing (BoxLayout) 对齐问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23100014/