2010-10-04 44 views
1

問題是,我無法使它成爲800x600的尺寸。換句話說,當我運行這個程序時,框架非常小,我無法做任何事情。如何讓我的GUI框架更大?

如何讓框架變大?

我已經設置了首選大小已經設置畫布邊界。

然後是什麼問題?

public class GameCanvas extends Canvas 
{ 
    private BufferStrategy buffer = null; 

    public GameCanvas() 
    { 
     setBounds(0, 0, 800, 600); 
     setIgnoreRepaint(true); 

     addKeyListener(new KeyInputHandler()); 

     requestFocus();  
    } 

    public void addNotify() 
    { 
     super.addNotify(); 
     this.createBufferStrategy(2); 
     buffer = this.getBufferStrategy(); 

     setBounds(0, 0, 800, 600); 
    } 
} 

public class GameGuiFrame extends JFrame 
{ 
    private JPanel panel = new JPanel(); 
    private GameCanvas canvas = new GameCanvas(); 

    public GameGuiFrame() 
    { 
     this.setName("My Game"); 

     this.pack(); 
     this.setResizable(false); 
     this.setVisible(true); 

     panel = (JPanel) this.getContentPane(); 
     panel.setPreferredSize(new Dimension(750,500)); 
     panel.setLayout(null); 
     panel.add(canvas); 
    } 
} 

public class GameManager 
{ 
    public static void runGameLoop() 
    { 
     GameGuiFrame container = new GameGuiFrame(); 

     container.addWindowListener(new WindowAdapter() 
     { 
      public void windowClosing(WindowEvent e) 
      { 
       System.exit(0); 
      } 
     }); 
    } 
} 

public class Main 
{ 
    public static void main(String [] args) 
    { 
     GameManager.runGameLoop(); 
    } 
} 

回答

5

嘗試打包您設置了內容窗格的首選大小。

1

您致電pack()會將幀(及其中的組件)設置爲其首選大小。但是,您尚未指定首選大小。我建議您將兩個電話撥到setBounds(),並在主要方法中調用setBounds()而不是pack()

2

與您的問題無關,但基於您發佈的代碼,它看起來像您已經複製了一些舊的AWT代碼,並且正在嘗試在Swing應用程序中使用它。

我建議你只使用Swing組件。不需要使用具有BufferStrategy的Canvas。只需使用默認情況下雙緩衝的JPanel。你複製的代碼片段是舊的,這不是它在Swing中完成的方式。

請勿使用空佈局。 Swing旨在與佈局經理一起使用。然後pack()方法將能夠正常工作。

沒有必要使用WindowListener來關閉框架。現在人們只使用:

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

另外,框架應該在組件添加到框架後變爲可見。

通常,您應該使用鍵綁定,而不是KeyListener來偵聽Swing應用程序中的鍵事件。

我建議你看看Swing tutorial以獲得更多關於上述概念的信息。