2013-05-12 196 views
-1

因此,我試圖製作一個橫跨我的整個程序,並具有約20像素的身高的面板。由於某種原因,只有一個小盒子就是面板。有誰能告訴我爲什麼它不能伸展到整個寬度?我對Java相當陌生,所以很抱歉,如果代碼有點混亂/錯誤。JPanel不伸展以填充屏幕

GridPane類

public GridPane() { 
    gbc = new GridBagConstraints(); 
    gbc.anchor = GridBagConstraints.NORTH; 
    gbc.weighty = 1.0; 
    horizontalGrid = new JButton(); 
    horizontalGrid.setText("Horizontal Grid"); 
    options = new JPanel(new BorderLayout()); 
    options.setBackground(Color.black); 
    options.add(horizontalGrid); 
    add(options, gbc); 
} 

遊戲類

public class Game extends JPanel implements ActionListener{ 
    //DECLARATIONS 
private static final long serialVersionUID = 1L; 
    public GridPane grid = new GridPane(); 
//DECLARATIONS END 
//CONSTRUCTOR 
public Game() { 
    this.add(grid);  
} 
//CONSTRUCTOR ENDS 
//MAIN METHOD 
public static void main(String[] args) { 
    JFrame frame = new JFrame(); 
    Game game = new Game(); 
    frame.setResizable(true); 
    frame.setAlwaysOnTop(true); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.add(game); 
    frame.pack(); 
    frame.setLocationRelativeTo(null); 
    frame.setVisible(true); 
} 
//MAIN METHOD ENDS 
//ACTION METHOD 
public void actionPerformed(ActionEvent e) { 
} 
+0

參考http://stackoverflow.com/questions/9212989/jpanels-dont-completely-stretch-to-occupy-the-available-space – 2013-05-12 23:01:20

+0

你設置'重量',但你錯過了它似乎。 ......「體重?」也許? – 2013-05-12 23:06:52

+0

好吧,我會直言不諱地指出 - 你在哪裏設置「weightx」? – 2013-05-12 23:22:57

回答

0

我修好了!事實證明,我們需要使用此代碼替換GridPane構造:

setBackground(Color.black); 

add(horizontalGrid); 

我不知道是什麼原因,但它的作品。