gpt4 book ai didi

java - 为 JPanel 内部的 JPanel 元素着色

转载 作者:行者123 更新时间:2023-12-02 03:31:38 25 4
gpt4 key购买 nike

我正在 Swing 中绘制棋盘。我创建了图 block (jpanel),然后尝试将组件添加到板上(另一个 jpanel)。每次添加图 block 时,我都会尝试设置颜色,黑色或白色。 Board有GridLayout。 Board 确实添加了 64 个图 block ,但只有其中一个图 block 获得了颜色,其余的图 block 获得了默认颜色。我尝试将图 block (jpanel)更改为按钮(JButton)(以查看组件是否添加到板上),程序确实向板上添加了 64 个按钮。所以我猜布局和添加组件没有问题,而是与更新颜色有关?

那么,当我将这些较小的 jpanel(tiles) 添加到较大的 Jpanel(Board) 中时,如何更改它们的颜色呢?

程序如下(不要介意配色方案,我实际上并不想要棋盘):

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);
}
}

最佳答案

这是错误的:

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

您填充的颜色没问题,但是在相对于 JPanel 的 xPos 和 yPos 处,这意味着颜色远离 JPanel 的实际显示区域。

解决方案:

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

关于java - 为 JPanel 内部的 JPanel 元素着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38021503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com