2013-04-23 27 views
0

我正在嘗試製作遊戲的菜單屏幕。我添加了兩個按鈕,播放和退出,目前正試圖弄清楚如何調整它們的大小。當我運行我的代碼時,按鈕幾乎是完全相同的大小(不同的是我想象的因爲文本)。我爲我的按鈕使用BoxLayout,我只是在這裏閱讀Why will BoxLayout not allow me to change the width of a JButton but let me change the height?爲什麼它只會調整寬度或高度,但它現在不會調整大小。在我的代碼中,我使用BoxLayout.PAGE_AXIS,我不知道這是否有所作爲,但是它沒有使用BoxLayout.Y_AXIS垂直調整大小。JButtons沒有調整大小以匹配他們的首選大小

這裏是我的代碼:

public class Stage extends JFrame { 
/* PRIVATE */ 
private JButton play, exit; 

// Setup the Menu screen. 
private void createMenuScreen() { 
    Container window = getContentPane(); 
    // window.setBackground(Color.BLACK); 
    JPanel menuScreen = new JPanel(); 
    menuScreen.setLayout(new BoxLayout(menuScreen, BoxLayout.PAGE_AXIS)); 
    window.add(menuScreen, "Center"); 

    play = new JButton("Play"); 
    play.setPreferredSize(new Dimension(20, 20)); 
    play.setAlignmentX(Component.CENTER_ALIGNMENT); 



    exit = new JButton("Exit"); 
    exit.setPreferredSize(new Dimension(100, 100)); 
    exit.setAlignmentX(Component.CENTER_ALIGNMENT); 
    menuScreen.add(play); 
    menuScreen.add(exit); 
} 

/* PUBLIC */ 
public Stage() { 
    // Setup the frame. 
    setSize(224, 288); 
    setLocationRelativeTo(null); // Centers the window. 
    setUndecorated(true); // Removes the Windows border. 
    setVisible(true); 

    createMenuScreen(); 
} 
} 

回答

1

嘗試使用setMaximumSize()方法

exit.setMaximumSize(new Dimension(100,100));

或者嘗試使用BorderLayout代替BoxLayout

+0

這工作,與BoxLayout的,但如何來? – James 2013-04-23 19:31:46

+0

[Box Layout Features](http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html#features) – 2013-04-23 19:39:32

+0

感謝您的幫助! – James 2013-04-23 19:42:15

相關問題