2015-06-20 64 views
0

===================
遊戲名稱Java:什麼佈局管理器最適合遊戲菜單?

播放
退出

============= ======

以上是我以前的遊戲菜單的樣子。我使用Box Layout來創建它,但它非常乏味。有沒有更好的佈局管理器,我可以使用?

這裏是那些詢問主窗格的代碼。

private JButton JB; 
private JButton EB; 
private JOptionPane JO; 

public StartUpWindow(){ 
    super("Pong"); 

    JPanel outside = new JPanel(); 
    JPanel inside = new JPanel(); 
    setLayout(new BorderLayout()); 



    outside.setLayout(new BoxLayout(outside, BoxLayout.LINE_AXIS)); 
    inside.setLayout(new BoxLayout(inside, BoxLayout.PAGE_AXIS)); 

    outside.add(Box.createHorizontalStrut(280)); 
    outside.add(inside); 
    outside.add(Box.createHorizontalStrut(20)); 

    inside.add(Box.createVerticalStrut(20)); 
    JLabel title = new JLabel("  "+"Pong"); 
    title.setFont(new Font("Serif", Font.BOLD, 40)); 
    inside.add(title); 
    inside.add(Box.createVerticalStrut(20)); 

    JButton btt1 = new JButton("Start"); 
    Dimension d = new Dimension(200,40); 

    btt1.setSize(d); 
    btt1.setMinimumSize(d); 
    btt1.setMaximumSize(d); 
    btt1.setPreferredSize(d); 

    JButton btt2 = new JButton("Credits"); 
    btt2.setSize(d); 
    btt2.setMinimumSize(d); 
    btt2.setMaximumSize(d); 
    btt2.setPreferredSize(d); 
    JButton btt3 = new JButton("Exit"); 
    btt3.setSize(d); 
    btt3.setMinimumSize(d); 
    btt3.setMaximumSize(d); 
    btt3.setPreferredSize(d); 

    inside.add(btt1); 
    btt1.addActionListener(this); 
    btt1.setActionCommand("start"); 

    inside.add(Box.createVerticalStrut(5)); 

    inside.add(btt2); 
    btt2.addActionListener(this); 
    btt2.setActionCommand("credits"); 

    inside.add(Box.createVerticalStrut(5)); 

    inside.add(btt3); 
    btt3.addActionListener(this); 
    btt3.setActionCommand("exit"); 

    inside.add(Box.createVerticalStrut(20)); 

    add(outside); 

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    this.setSize(800,600); 
    this.setVisible(true); 
    this.setResizable(false); 
    this.setLocation(450,200); 

    inside.setBackground(Color.GRAY); 
    outside.setBackground(Color.GRAY); 


} 
+0

爲什麼「盒子」單調乏味?你能顯示你的代碼嗎? – markspace

+0

我更喜歡'GridBagLayout'來獲得一個簡單的居中菜單,標題和下面的按鈕。 – CoderMusgrove

+0

爲什麼你想要所有的按鈕正好是200x40像素? – immibis

回答

3

我同意的BoxLayout是乏味的,但我欣賞其相對簡單。

另一種快捷方便的選擇是使用「javax.swing.Box」類,而不是直接使用佈局管理器。

Box box = Box.createVerticalBox(); 
box.add(new JLabel("Game")); 
box.add(Box.createVerticalStrut(20)); 
box.add(new JLabel("Button 1")); 
box.add(new JLabel("Button 2")); 

JFrame frame = new JFrame(); 
frame.add(box); 
frame.pack(); 
frame.setVisible(true); 

Box提供了許多有用的方法。您可以使用它來創建垂直和水平方框,創建「支柱」以保留水平和垂直空間,並在佈局增長時創建「膠水」以填充可用空間。

當然你也可以使用GridBagLayout,但我傾向於保留它以適應更復雜的佈局。 Box和他的堂兄BoxLayout通常對於簡單的佈局來說足夠好,並且對於維持應用程序理解和調試的新程序員來說很容易。

0

爲什麼不簡單地使用沒有佈局,而是使用Graphics對象繪製所有對象?


你可以很容易地通過創建綁定到Window對象(調用對後者createBufferStrategy)一BufferStrategy然後調用幾個簡單的方法可以輕鬆地刷新屏幕實現這一目標。

這也意味着在玩遊戲時再編碼遊戲的顯示會更簡單。


BufferStrategy還允許使用翻頁和其他形式的緩衝的當應用程序處於全屏獨佔模式,使其能夠非常迅速地刷新屏幕,在許多應用中。