我有一个关于布局一些swing组件的问题。
比方说,我有一个包含JLabel和JTextField的JPanel。我希望将JLabel绘制在JPanel的最左侧,将JTextField绘制在JPanel的最右侧。我试着使用BoxLayout和水平胶水,但我不能让它工作。有人能解释一下应该怎么做吗?顺便说一句,我还应该能够设置JTextField的大小,它将从右向左增长。
编辑:这是我的类,非常简单。
public class TextField extends JPanel {
    private JLabel label;
    private JTextField textField;
    public TextField(String labelText){
        this.label = new JLabel(labelText);
        this.textField = new JTextField("");
        Box horizontalBox = Box.createHorizontalBox();
        horizontalBox.add(label);
        horizontalBox.add(Box.createHorizontalGlue());
        horizontalBox.add(textField);
        add(horizontalBox);
    }
}发布于 2009-10-27 07:14:11
您还可以使用边框布局,并使用BorderLayout.WEST选项添加标签,使用BorderLayout.EAST选项添加TextField。
发布于 2009-10-27 07:35:34
调试swing UI的最佳方法之一是向组件添加可见边框,以便更好地了解正在发生的事情。
尝试在创建horizontalBox后添加此内容
horizontalBox.setBorder(BorderFactory.createLineBorder(Color.black));您很可能会发现,您的TextField缩小到了显示传递给构造函数的任何文本所需的绝对最小大小和JTextField的最小大小(基本上就是一个可见的字符空间)。
现在尝试将以下代码添加到构造函数中:
horizontalBox.setPreferredSize(new Dimension(400, 40));然后试着用支柱代替胶水:
horizontalBox.add(Box.createHorizontalStrut(30));也就是说,我认为最大的问题是你正在使用一个JPanel,然后向它添加一个盒子组件,这使得调整组件的大小变得有问题。
试试这个,看看它对你是否有效:
public TextField(String labelText){
    this.label = new JLabel(labelText);
    this.textField = new JTextField("");
    this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
    this.setBorder(BorderFactory.createLineBorder(Color.black));  // debug
    this.add(label);
    this.add(Box.createHorizontalStrut(30));
    this.add(textField);
}附注:
您真的想重新考虑该JPanel扩展的名称。也许TextFieldDisplay或TextFieldPanel更合适。
发布于 2009-10-27 06:48:58
我试过使用BoxLayout和水平胶水,但我不能让它工作。有人能解释一下应该怎么做吗?
这并不是什么诀窍。请阅读How to Use Box Layout上的Swing教程以获取工作示例。
如果它仍然不能工作,那么你需要发布你的SSCCE,因为我们无法猜测你可能做错了什么。
https://stackoverflow.com/questions/1627719
复制相似问题