Java DrawRectangle在图形下方而不是上方绘制矩形
当我试图在一块上面涂有蓝色矩形的板上绘制矩形时,我看到矩形是在蓝色矩形下绘制的,但绘制红色矩形的方法是在红色矩形后调用的Java DrawRectangle在图形下方而不是上方绘制矩形,java,swing,rectangles,Java,Swing,Rectangles,当我试图在一块上面涂有蓝色矩形的板上绘制矩形时,我看到矩形是在蓝色矩形下绘制的,但绘制红色矩形的方法是在红色矩形后调用的 @Override protected void paintComponent(Graphics g) { super.paintComponent(g); //To change body of generated methods, choose Tools | Templates. //this method paints the blue boar
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
//this method paints the blue board
pintarTablero(getGraphics(), tableroMio, 100, 200);
//red rectangle
g.setColor(Color.red);
g.drawRect(200, 200, 200, 200);
g.fillRect(200, 200, 200, 200);
}
public void pintarTablero(Graphics g, int tab[][], int x, int y) {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (tab[i][j] == 0) {
// g.setColor(Color.blue);
//g.fillRect(x + i * 30, y + j * 30, 30, 30);
// g.setColor(Color.black);
g.drawRect(x + i * 30, y + j * 30, 30, 30);
}
}
}
}
@覆盖
受保护组件(图形g){
super.paintComponent(g);//若要更改生成方法的主体,请选择工具|模板。
//这种方法可以画蓝牌
pintarTablero(getGraphics(),tableroMio,100200);
//红色矩形
g、 setColor(Color.red);
g、 drawRect(200200200200200);
g、 fillRect(200200200200200);
}
公共无效pintarTablero(图形g,整数选项卡[],整数x,整数y){
对于(int i=0;i<8;i++){
对于(int j=0;j<8;j++){
如果(表[i][j]==0){
//g.setColor(颜色为蓝色);
//g、 fillRect(x+i*30,y+j*30,30,30);
//g.setColor(颜色为黑色);
g、 drawRect(x+i*30,y+j*30,30,30);
}
}
}
}
我怀疑红色矩形的坐标是这里的问题所在。尝试一个fillRect(0,0200200)
它似乎被画在蓝色正方形旁边,从
JPanel
或任何JComponent
中剪掉
我强调,似乎鉴于
pintarTablero
不会做任何乱七八糟的事情,比如更改剪辑或其他事情,我的建议是更改这一行:
pintarTablero(getGraphics(), tableroMio, 100, 200);
为此:
pintarTablero(g, tableroMio, 100, 200);
因为您会发现交给paintComponent的图形对象与getGraphics返回的图形对象不同。如果尝试将以下内容插入到paintComponent中:
System.out.println(g == getGraphics());
您会发现它打印的是
false
,这种交互可能是问题的根源。无论如何,您都不应该在paintComponent中使用getGraphics方法。您不需要使用getGraphics,只需将g传递给您的方法即可。如果你真的想要一个副本,你可以使用g.create(),但一定要处理()副本。这将有助于了解蓝色矩形绘图代码的功能。public void pintarTablero(Graphics g,int tab[]],int x,int y){for(int i=0;i<8;i++){for(int j=0;j<8;j++){if(tab[i][j]=0){//g.setColor(Color.blue);//g.fillRect(x+i*30,y+j*30,30,30);/g.setColor(Color.black);g.drawRect(x+i*30,y+j*30,30,30);}我的建议是按照我之前的建议,使用交给paintComponent的图形对象,因为它与getGraphics方法返回的对象不同。