2014-05-05 129 views
1

我是Java swing庫的新手,我目前在設置JFrame的背景時遇到了一些麻煩。Java setBackground()混淆

我已閱讀jframe-setbackground-not-working-why及其內的鏈接,但似乎並不適合此處。

這裏是我的代碼:

public class Board extends JPanel{ 

    public enum pointType{ 
     EMPTY, 
     CARRIER, 
     BALL; 
    } 

    private class Point{ 
     int x; 
     int y; 
     pointType type; 

     public void paint (Graphics2D g2){ 
      // color changes depends on pointType 
      g2.setColor(Color.WHITE); 
      g2.fillOval(x,y,25,25); 
     } 
    } 

    Point[][] myBoard; 

    public Board(){ 
     //constructor, myBoard = 2d List of points 
    } 

    //.. other methods and class variables 

    public void paint(Graphics g){ 
     Graphics2D g2 = (Graphics2D) g; 
     for(int k =HEIGHT; k>=0; k--){ 
      for(int i=WIDTH; i>=0; i--){ 
       // call paint method for each points on board 
       myBoard[i][k].print(g2); 
      } 
     } 
    } 

    public static void main(String[] args){ 
     Board board = new Board(); 
     JFrame myFrame = new Jframe("Game"); 

     myFrame.add(board); 
     board.setBackground(Color.YELLOW); 
     myFrame.setVisible(true); 

     mtFrane.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 
} 

我的代碼成功打印所有的點根據自己的pointType,但主板的顏色設置不正確(還是默認背景)。

所以這裏的問題:

1)我應該如何正確地設置背景是什麼?

2)我覺得我的代碼沒有正確使用JPanels/JFrames/Graphics,如果是這樣的話,關於如何改進我的代碼結構的任何建議?而不是

+2

沒有,請小心 - 這是'的paintComponent(圖形G)''不paintComponents' - *** ***無最後的's' –

+0

要設置JPanel的背景,請在其構造函數中調用'setBackground(Color c)'。 –

回答

2

使用paintComponent()paint()

public class Board extends JPanel{ 
    @Override 
    public void paintComponent(Graphics g){ 
     super.paintComponent(g); 
     ... 
    } 
} 

欲瞭解更多信息看看下面的帖子:

enter image description here

+0

點或板或兩者? – user1948847

+0

我正在更新我的帖子。你能等一下嗎? – Braj

+0

***再次***,它是paintComponent不paintComponent!這是一個重大的錯誤。 –

1

JPanel默認paintComponent()方法使用存儲在JPanel的實例變量的背景色;但是,您重寫的paintComponent()方法不使用實例變量,因此使用setBackground()更改它將不會執行任何操作。

如果你想堅持重寫paintComponent()方法,你應該在paintComponent()方法中用你想要的顏色繪製一個填充JPanel的整個區域的方框。

BoardpaintComponent()方法是這樣的:

@Override 
public void paintComponent(Graphics g){ 
    super.paintComponent(g); 
    Graphics2D g2 = (Graphics2D) g; 
    g2.setColor(Color.YELLOW); 
    g2.fillRect(0, 0, getWidth(), getHeight()); // Fill in background 

    // Do everything else 
    for(int k =HEIGHT; k>=0; k--){ 
     for(int i=WIDTH; i>=0; i--){ 
      // call paint method for each points on board 
      myBoard[i][k].print(g2); 
     } 
    } 
} 
+0

在這個應用程序中,它看起來像用戶不打算添加任何組件到'JPanel';更新後。 – APerson

+0

我剛剛更新了'paint(Graphics)'到'paintComponent(Graphics')。 – APerson

+0

現在請更改超級方法調用。 –