着色JPanel内部的JPanel元素

时间:2016-06-24 20:20:48

标签: java swing jpanel paintcomponent

我在Swing画一局棋盘。我创建了tile(jpanel),然后尝试将组件添加到board(另一个jpanel)。每次添加图块时,我都会尝试设置颜色,黑色或白色。 Board有GridLayout。 Board确实会添加64个图块,但只有一个图块会显示颜色,其余图块会显示默认颜色。我尝试将瓷砖(jpanel)更改为按钮(JButton)(以查看组件是否添加到板上),程序确实向电路板添加了64个按钮。所以我猜测布局和添加组件没有问题,而是更新颜色?

那么当我将它们添加到更大的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);
        }
    }

1 个答案:

答案 0 :(得分:2)

这是错误的:

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

您正在填充颜色,但xPos和yPos 相对于此JPanel ,意味着颜色远离JPanel的实际显示区域。

解决方案:

  • 将xPos和yPos更改为0和0
  • 或者最好只在构造函数中调用setBackground(...)