我需要在GUI中对齐复选框,但是我找不到正确的命令或方法。我写了一个简单易懂的简短例子:
public class GUI {
JFrame window = new JFrame();
JPanel mainPanel = new JPanel();
JPanel[] rowPanel = new JPanel[5];
JCheckBox[] check = new JCheckBox[5];
public GUI () {
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setExtendedState(window.MAXIMIZED_BOTH);
window.setVisible(true);
window.add(mainPanel);
mainPanel.setLayout(new GridLayout(5, 1));
for(int i = 0; i < 5; i++)
{
rowPanel[i] = new JPanel();
mainPanel.add(rowPanel[i]);
}
check[0] = new JCheckBox("red");
check[1] = new JCheckBox("violet");
check[2] = new JCheckBox("pink");
check[3] = new JCheckBox("magenta");
check[4] = new JCheckBox("every color");
for(int i = 0; i < 5; i++)
{
rowPanel[i].add(check[i]);
}
}
}
我尝试了.setHorizontalTextPosition()
和.setHorizontalAlignment()
,但都没有效果。我希望所有的盒子在标签的右侧垂直对齐。
答案 0 :(得分:3)
停止添加所有这些面板。使用一个面板,并将复选框添加到该面板,并在该面板上设置对齐。我修改了你的GUI构造函数。
public GUI() {
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setExtendedState(window.MAXIMIZED_BOTH);
window.setVisible(true);
window.add(mainPanel);
mainPanel.setLayout(new GridLayout(5, 1));
mainPanel.setAlignmentY(JComponent.LEFT_ALIGNMENT);
check[0] = new JCheckBox("red");
check[1] = new JCheckBox("violet");
check[2] = new JCheckBox("pink");
check[3] = new JCheckBox("magenta");
check[4] = new JCheckBox("every color");
for (int i = 0; i < 5; i++) {
mainPanel.add(check[i]);
}
}