2016-11-24 87 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