2016-06-24 26 views
0

我在Swing畫一個棋盤。我創建了瓷磚(jpanel),然後嘗試將組件添加到電路板(另一個jpanel)。每次添加一個貼圖時,我都嘗試設置一種顏色,無論是黑色還是白色。董事會有GridLayout。電路板確實添加了64個瓷磚,但只有一個瓷磚獲得了一種顏色,其餘的都獲得了默認顏色。我嘗試將瓷磚(jpanel)更改爲按鈕(JButton)(以查看是否將組件添加到板上),並且該程序確實爲板添加了64個按鈕。所以我猜測在佈局和添加組件方面沒有問題,而是需要更新顏色?JPanel裏面的着色JPanel元素

那麼當我將它們添加到更大的Jpanel(Board)時,如何更改這些較小的jpanel(tile)的顏色?

程序如下(不介意的配色方案,我其實不願意棋盤):

class Tile extends JPanel{ 

     private final int width = 50; 
     private final int height = 50; 
     Color tileColor; 
     int xPos, yPos; 


     public Tile(int xPos, int yPos, Color tileColor){ 

      this.xPos = xPos; 
      this.yPos = yPos; 
      this.tileColor = tileColor; 

     } 
     public Dimension getPreferredSize(){ 
      return new Dimension(width, height); 
     } 

     protected void paintComponent(Graphics g){ 
      super.paintComponent(g); 
      g.setColor(tileColor); 
      g.fillRect(xPos, yPos, getWidth(), getHeight()); 

     } 

    } 

    class Board extends JPanel{ 

     private final int width = 400; 
     private final int height = 400; 

     private int numTiles = 8; 
     private final Color black = Color.BLACK; 
     private final Color white = Color.WHITE; 

     private final int hGap = 2; 
     private final int vGap = 2; 


     public Board(){ 

      setLayout(new GridLayout(numTiles, numTiles,hGap, vGap)); 
      setBackground(Color.CYAN); 

      Color tileColor; 
      int yPos = 0; 
      for(int i = 0; i < numTiles; i++){ 

       int xPos = 0; 
       for(int j = 0; j < numTiles; j++){ 
        if(j % 2 == 0) 
         tileColor = black; 
        else 
         tileColor = white; 


        add(new Tile(xPos, yPos, tileColor)); 
        xPos += 50; 
       } 
       yPos += 50; 
      } 
     } 



     public Dimension getPreferredSize(){ 
      return new Dimension(width,height); 
     } 
    } 

回答

2

這是錯誤的:

g.fillRect(xPos, yPos, getWidth(), getHeight()); 

這裏要填寫顏色沒問題,但在xPos和yPos 相對於此JPanel,這意味着顏色遠離JPanel的實際顯示區域。

解決方案:

  • 變化XPOS和yPos爲0和0
  • 或者更好的只是調用構造函數setBackground(...)