2014-12-11 58 views
0

在創建完全黑色的窗口後,右側和底部邊緣會出現白色。我可能做錯了什麼?窗口右側和底部邊緣的空白位置

這是我做的窗口的初始化構造函數: -

public Panel() 
    { 
     Thread t = new Thread(this); 
     addKeyListener(this); 
     setFocusable(true); 
     this.setPreferredSize(new Dimension(gameWidth, gameHeight)); 
     JFrame f = new JFrame("AlienBusters"); 
     f.add(this); 
     f.pack(); 
     f.setLocationRelativeTo(null); 
     f.setResizable(false); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.setVisible(true); 
     t.start(); 
    } 

這是塗料方法,其中我做了窗口黑: -

@Override 
    public void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 
     g.setColor(Color.BLACK); 
     g.fillRect(0, 0, gameWidth, gameHeight); 
    } 
+1

請勿稱呼您的班級「面板」。有一個類名的AWT組件,它很混亂。你的班級名稱應該更具描述性。 – camickr 2014-12-11 06:10:55

回答

2

五件事...

  1. 調用setResizablepack,不是一個好主意,setResizable可以改變t他框架邊框大小,從而影響到可用內容大小...
  2. 使用KeyListener,認真,看到How to Use Key Bindings並保存youreself頭部疼痛...
  3. 依託神奇數字,而不是imperical值,g.fillRect(0, 0, gameWidth, gameHeight);應該是g.fillRect(0, 0, getWidth(), getHeight());或更好的是,簡單地使用setBackground(Color.BLACK)並通過super.paintComponent免費得到...和paintComponent應該是protected;)
  4. 致電setPreferredSize。這意味着尺寸可能會改變,這可能不是你真正想要的。相反,請改爲getPreferredSize。有關更多詳細信息,請參閱Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
  5. 在構件的構造函數中構造框架時,構件不應該在意它將如何顯示,而應該只關注它的工作。
相關問題