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