2015-04-04 70 views
0

2列我有在Java代碼:佈局在Java

gamePanel = new JPanel(); 
    gamePanel.setLayout(new FlowLayout()); 
    scrollPane = new JScrollPane(gamePanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); 
    scrollPane.setBounds(5,50,300,100); 

    JButton btn1 = new JButton("btn 1"); 
    JButton btn2 = new JButton("btn 2"); 
    JButton btn3 = new JButton("btn 3"); 
    JButton btn4 = new JButton("btn 4"); 
    JButton btn5 = new JButton("btn 5"); 
    gamePanel.add(btn1); 
    gamePanel.add(btn2); 
    gamePanel.add(btn3); 
    gamePanel.add(btn4); 
    gamePanel.add(btn5); 

我想要的結果是:

-------------------------- 
| Name1  | Button 1 | 
-------------------------- 
| Name2  | Button 2 | 
-------------------------- 
| Name3  | Button 3 | 
-------------------------- 

如果超過JPanel的大小,必須使用滾動窗格。

在我的代碼的結果是:

--------------------------------------------------- 
| Name1  | Button 1 | Name2  | Button 2 | 
--------------------------------------------------- 
+0

GridLayout,GridBagLayout或MigLayout,您的選擇。 – 2015-04-04 16:20:17

+0

如果我使用GridLayout,這些按鈕正好處於JPanel大小。我需要讓它滾動。 – 2015-04-04 16:24:01

+0

那麼爲什麼不GridBagLayout - 當你嘗試這個時會發生什麼? – 2015-04-04 17:52:44

回答

0

JPanels使用的FlowLayout默認情況下,所以你不需要申報。嘗試GridLayout,像這樣:

JPanel gamePanel = new JPanel(); 
    gamePanel.setLayout(new GridLayout(3,2,2,2)); 


    JButton btn1 = new JButton("btn 1"); 
    JLabel name1 = new JLabel("name1"); 
    JButton btn2 = new JButton("btn 2"); 
    JLabel name2 = new JLabel("name2"); 
    JButton btn3 = new JButton("btn 3"); 
    JLabel name3 = new JLabel("name3"); 

    gamePanel.add(name1); 
    gamePanel.add(btn1); 
    gamePanel.add(name2); 
    gamePanel.add(btn2); 
    gamePanel.add(name3); 
    gamePanel.add(btn3);