在 Java Swing 应用程序中对首选项面板进行编程时,我遇到了似乎无法解决的问题。
SSCCE:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
/**
* demonstrates the issue at hand
*/
public class Probs extends JFrame {
/**
*
*/
private static final long serialVersionUID = -2320457631507860940L;
JCheckBox one = new JCheckBox("Checkbox One");
JCheckBox two = new JCheckBox("Checkbox Two");
JCheckBox three = new JCheckBox("Checkbox Three");
JCheckBox four = new JCheckBox("Checkbox Four");
final static int BORDER = 10;
final static int WIDTH = 440;
final static int DESC_HEIGHT = 30;
public Probs () {
JTabbedPane options = new JTabbedPane();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//set up the main panel
JPanel pan = new JPanel();
pan.setBorder(BorderFactory.createEmptyBorder(Probs.BORDER, Probs.BORDER, Probs.BORDER, Probs.BORDER));
pan.setLayout(new BoxLayout(pan, BoxLayout.Y_AXIS));
//construct the descriptor subpanel
JPanel desc = new JPanel();
desc.setLayout(new BorderLayout());
desc.add(new CustomLab("Options Title Goes Here"));
JSeparator sep1 = new JSeparator();
desc.add(sep1, BorderLayout.SOUTH);
desc.setPreferredSize(new Dimension(Probs.WIDTH, Probs.DESC_HEIGHT));
desc.setMinimumSize(new Dimension(Probs.WIDTH, Probs.DESC_HEIGHT));
desc.setMaximumSize(new Dimension(Probs.WIDTH, Probs.DESC_HEIGHT));
pan.add(desc);
//basic options
JPanel basic = new JPanel();
basic.setLayout(new BoxLayout(basic, BoxLayout.Y_AXIS));
basic.setBorder(BorderFactory.createTitledBorder("Basic"));
basic.add(one);
basic.add(two);
basic.add(three);
basic.add(four);
basic.setPreferredSize(new Dimension(Probs.WIDTH, basic.getPreferredSize().height));
basic.setMinimumSize(new Dimension(Probs.WIDTH, basic.getPreferredSize().height));
basic.setMaximumSize(new Dimension(Probs.WIDTH, basic.getPreferredSize().height));
pan.add(basic);
options.addTab("Panel One", pan);
add(options);
setSize(500, 500);
setVisible(true);
}
public static void main(String[] args) {
new Probs();
}
}
在我的机器(带有 Java 7 的 OSX Mountain Lion)上,产生类似于 this 的结果。我希望基本面板一直位于左侧(我已经尝试了 basic.setAlignmentX(JComponent.LEFT_ALIGNMENT);
但无济于事(该行代码没有效果)。此外,我已经检查了诸如
也无济于事。
有趣的是,如果删除了 desc 面板(因此 pan.add(desc);
被注释掉),则基本面板会正确对齐,如 所示。 .
如何正确左对齐 desc 和基本 jpanels(以及您在代码中看到的任何其他错误)。
最后,(有点切线):指定最小值、最大值、和首选尺寸是在 BoxLayout 中调整 JPanel 大小的正确方法(看起来很不优雅)?
最佳答案
使用容器将添加到 BoxLayout 的两个组件的对齐 x 设置为 Component.LEFT_ALIGNMENT:
JPanel desc = new JPanel();
// ....
desc.setAlignmentX(Component.LEFT_ALIGNMENT);
// ......
pan.add(desc);
JPanel basic = new JPanel();
// ..........
basic.setAlignmentX(Component.LEFT_ALIGNMENT);
pan.add(basic);
<小时/>
编辑
我刚刚查看了您的链接,其中两个都已经提到了这一点。那么这对你来说怎么不起作用呢?我想这个问题将/应该作为重复问题关闭。
关于Java BoxLayout 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22572330/