摆动 BoxLayout 不工作

swing BoxLayout not working

我在这里阅读了很多主题,但我无法 window 使用我想要的布局。 我只是希望我所有的图形对象都像这里的第一张图片一样排成一行: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();
}
}

我只想每行一个按钮。

A BoxLayout 将遵循组件的 minimum/maximum 大小。

出于某种原因,文本字段的最大高度没有限制,因此文本字段获得了所有可用的 space。

所以你可以这样做:

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 更改。

相反,当您 add/remove 来自可见 GUI 的组件时,您应该使用:

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