【问题标题】:swing BoxLayout not working摆动 BoxLayout 不起作用
【发布时间】:2016-11-24 00:08:49
【问题描述】:

我在这里阅读了很多主题,但我无法按照我想要的布局制作我的窗口。 我只是希望我的所有图形对象都像这里的第一张图片一样排成一行:http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html

我尝试过 GridLayout,但它仍然使我的第一个按钮变大,然后,随着我添加文本字段,它变得越来越小?!

这是我没有所有导入的代码:

public class TestScrollPane extends JFrame implements ActionListener{
Dimension dim = new Dimension(200 , 50);
JButton button;
JPanel panel = new JPanel();
JScrollPane scrollpane = new JScrollPane(panel);

public TestScrollPane(){
    scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    this.add(scrollpane);

    //panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

    this.setSize(300, 400);
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);

    button = new JButton("click me");
    button.setPreferredSize(dim);
    panel.add(button);
    button.addActionListener(this);
}


public void actionPerformed(ActionEvent e){
    if(e.getSource() == button ){

        JTextField txt = new JTextField(); // we add a new button
        txt.setPreferredSize(dim);
        panel.add(txt);

        SwingUtilities.updateComponentTreeUI(this); // refresh jframe
    }
}

public static void main(String[] args){
    TestScrollPane test = new TestScrollPane();
}
}

我只想每行有一个按钮。

【问题讨论】:

    标签: java swing jpanel jscrollpane


    【解决方案1】:

    BoxLayout 将遵循组件的最小/最大尺寸。

    由于某种原因,文本字段的最大高度是无限的,因此文本字段可以获得所有可用空间。

    所以你可以这样做:

    JTextField txt = new JTextField(10); // we add a new button
    //txt.setPreferredSize(dim); // don't hardcode a preferrd size of a component.
    txt.setMaximumSize(txt.getPreferredSize());
    

    还有:

    //SwingUtilities.updateComponentTreeUI(this); // refresh jframe
    

    不要使用上述方法。这用于 LAF 更改。

    当您从可见的 GUI 添加/删除组件时,您应该使用:

    panel.revalidate();
    panel.repaint();
    

    【讨论】:

    • 谢谢老兄,我知道这是关于preferredsize的,但我认为button.setPreferredSize(dim);足够了。
    • @zogota but I thought that button.setPreferredSize(dim); was sufficient. - 你应该摆脱这种说法。您不应该试图控制任何组件的首选大小。
    • 感谢您的提示!我尝试了 button.setMinimumSize(dim) 并且我对文本字段做了同样的事情,但是当我添加文本字段时,按钮会减小它的大小,它们也会减小,直到某个大小低于 昏暗 维度。发生了什么?
    • @zogota,当您创建 JTextField 时,您应该使用:JTextField textField = new JTextField(10)。该数字将建议文本字段的首选大小,使其至少显示 10 个字符。
    • 它适用于 column 参数,但这是否意味着我不能硬核我的文本字段的高度?
    猜你喜欢
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多