在 java Graphics 对象中设置背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32100567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:39:59  来源:igfitidea点击:

Set background color in java Graphics object

javagraphicscolorsbackgroundborder

提问by Panadol Chong

Good day,

再会,

Know that in Java Graphics object, we can user the setColor()method to set the object color. But this is only apply to the object border. Is it anyway to set color for the whole object? I means the background of the Graphics object.

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

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

    }

Kindly advise.

好心提醒。

采纳答案by Madhawa Priyashantha

use fillRect()method .

使用fillRect()方法。

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

from javadoc

来自javadoc



drawRect()

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.

绘制指定矩形的轮廓。矩形的左右边缘位于 x 和 x + 宽度处。顶部和底部边缘位于 y 和 y + 高度。矩形是使用图形上下文的当前颜色绘制的。

fillRect()

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.

填充指定的矩形。矩形的左右边缘位于 x 和 x + 宽度 - 1。顶部和底部边缘位于 y 和 y + 高度 - 1。生成的矩形覆盖区域宽度像素宽 x 高度像素高。矩形使用图形上下文的当前颜色填充。



" this is only apply to the object border" because drawRectdraw the outlines only. " Is it anyway to set color for the whole object?" well you misunderstand . and setColor()set the color to what you draw if you draw a outline then you can see outline only and it's not because of setColor()set colors to border .

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