我在这里阅读了很多主题,但我无法使用我想要的布局来制作我的窗口。 我只是希望所有图形对象都采用行样式,如第一张图片所示: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();
}
}
我只想每行有一个按钮。
最佳答案
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();
关于java - swing BoxLayout 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40776184/