Java Swing(BoxLayout)对齐问题 [英] Java Swing (BoxLayout) alignment issues
问题描述
对于Java Swing来说,我是一个非常陌生的人,在布局合理的过程中我遇到了很多问题。我已经在该网站上签出了google甚至其他答案,但是我发现没有任何信息似乎可以解决该问题。这是我努力的结果:
I am extremely new to Java Swing, and I'm having quite a bit of issues getting a nice layout going. I have checked out google, and even other answers on this website, but no information I find seems to solve the issue. Here is the result of my efforts:
如您所见,标签,文本字段和按钮都未对齐。我的目标是所有人都具有相同的左边框,按钮和文本字段具有相同的右边框,这些左,右边框与左,右边框的距离均相同
As you can see, the label, text field, and button are all out of alignment. It is my goal for all of them to have the same left-hand border, and for the button and text field to have the same right-hand border, with these left and right hand borders being each the same distance from the left and righthand sides of my window.
这是我代码的重要部分:
Here are the important parts of my code:
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中:
And, in 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);
}
有人对此有一个简单的解决方案吗?我在这里做什么错了?
Does anyone have a simple solution to this? What am I doing wrong here?
非常感谢!
-乔治·奥茨·拉森(Georges Oates Larsen)
--Georges Oates Larsen
推荐答案
阅读如何使用BoxLayout 作为使用BoxLayout的基础知识以及有关对齐问题的部分。
Read the section from the Swing tutorial on How to Use BoxLayout for the basics of using a BoxLayout as well as a section on alignment issues.
基本上,您需要确保所有组件的alignmentX值都设置为左对齐。
Basically you need to make sure the alignmentX value of all components is set to be left aligned.
也:
- 不要使用setPreferredSize()设置组件的大小。每个Swing组件将确定其自己的首选大小。
- 使用Java命名约定。变量名称不应以大写字母开头。
这篇关于Java Swing(BoxLayout)对齐问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!