2016-11-24 86 views
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(); 
} 
} 

我只是想有每行一个按钮。

回答

1

A 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(); 
+0

感谢伙计,我知道这是一些有关首选大小,但我认为button.setPreferredSize(DIM);就足够了。 – zogota

+0

@zogota'但我认为button.setPreferredSize(dim);是足够的。“ - 你应该摆脱这种说法。您不应该试图控制任何组件的首选大小。 – camickr

+0

谢谢你的提示!我试过_button.setMinimumSize(dim)_并且我对textfield做了同样的处理,但是当我添加textfields时,按钮会减小它的大小,所以它们会一直延伸到比_dim_ Dimension更小的特定大小。发生什么事 ? – zogota