English 中文(简体)
图形是否在油漆元( Graphics) 中绘制?
原标题:Graphics not drawing in paintComponent(Graphics)?

我在为我的应用程序制作一个自定义的滚动组件,我开始用 公共空漆Component (Graphics g) 来绘制东西。除了我无法绘制任何矩形之外,一切都很好。我认为问题在于 getX () getY () 部分,但我不确定这一点。这里的代码是:

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (mouseEntered) {
        g.setColor(HIGHLIGHTED_COLOR);
    } else {
        g.setColor(BACKGROUND_COLOR);
    }

    g.fillRect(getX(), getY(), getWidth(), getHeight());


    //Draw rest of stuff (works fine)

API说,它应该这样使用: g.fillRect(x, y, y, 宽度, 高度) , 这就是我正在做的。

其余的画很完美 但我不明白为什么画不出来,有什么建议吗?

最佳回答

我不清楚您是如何定义 concommonent 的,但 concommonent s getX () 方法的默认值是 concommonent 左上角(与根元件相对)的 X 坐标。

当您在 Swing 中绘制 < em> component s < code>paintComponent (Graphics) 方法时,您要绘制的 < em > graphics 上方背景的起源通常位于 < tengleem > Concompent 本身的左上端,而不是根 < em > component 。

因此,通过做这个呼吁:

g.fillRect(getX(), getY(), getWidth(), getHeight());

您可能会在 < em> component 的剪辑边框外绘制矩形!

(例如,如果组件位于100、100处,宽度为20,高度为20,则您正在绘制的矩形在 < 坚固> 绝对 < /坚固 > 坐标下,位于 < code> (200, 200) 至 < code> (220,220) )

如果您想要绘制一个包含整个组件的矩形, 您可能想要尝试一个类似此的矩形 :

g.fillRect(0, 0, getWidth(), getHeight());

这将从源( 很可能是元件的左上角) 到元件的宽度和高度 。

(举上一个示例: 组件为 100, 100, 宽/ 高度为 20, 矩形将绘制为 < code> (100, 100) 到 < code> (120, 120) )

希望这有帮助 =)

问题回答

暂无回答




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签