0
我已经阅读了很多主题,但我无法使用我想要的布局创建窗口。 我只是希望我所有的图形对象是在一排的风格像第一张图片浏览:http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html摆动BoxLayout不能正常工作
我试过网格布局,但它仍然使我的第一个按钮巨人,然后,我添加文本框,它变得更小和更小?!
这里是我的代码,而所有进口:
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();
}
}
我只是想有每行一个按钮。
感谢伙计,我知道这是一些有关首选大小,但我认为button.setPreferredSize(DIM);就足够了。 – zogota
@zogota'但我认为button.setPreferredSize(dim);是足够的。“ - 你应该摆脱这种说法。您不应该试图控制任何组件的首选大小。 – camickr
谢谢你的提示!我试过_button.setMinimumSize(dim)_并且我对textfield做了同样的处理,但是当我添加textfields时,按钮会减小它的大小,所以它们会一直延伸到比_dim_ Dimension更小的特定大小。发生什么事 ? – zogota