在 java 图形对象中设置背景颜色

Set background color in java Graphics object

美好的一天,

知道在JavaGraphics对象中,我们可以使用setColor()方法来设置对象颜色。但这仅适用于对象边框。无论如何要为整个对象设置颜色?我指的是 Graphics 对象的背景。

void draw(Graphics g)
    {
        g.setColor(color);
        g.drawRect(left, right, width, height);

    }

请指教。

使用fillRect()方法。

 g.fillRect(left, right, width, height);

来自 javadoc


drawRect()

Draws the outline of the specified rectangle. The left and right edges of the rectangle are at x and x + width. The top and bottom edges are at y and y + height. The rectangle is drawn using the graphics context's current color.

fillRect()

Fills the specified rectangle. The left and right edges of the rectangle are at x and x + width - 1. The top and bottom edges are at y and y + height - 1. The resulting rectangle covers an area width pixels wide by height pixels tall. The rectangle is filled using the graphics context's current color.


" 这仅适用于对象边框" 因为drawRect 仅绘制轮廓。 ” 是否要为整个对象设置颜色?”你误会了。并且 setColor() 将颜色设置为您绘制的颜色 如果您绘制轮廓,那么您只能看到轮廓,这不是因为 setColor() 将颜色设置为边框 .