英文:
JComponent not being drawn on JLayeredPane, JPanel is
问题
我已经将一个 JLayeredPane
添加到了一个 JFrame
中。在该面板上,我添加了一个具有重载的 paintComponent(Graphics g)
方法的 JComponent
,该方法在执行其他操作时会调用 super.paintComponent(g)
。这个 JComponent
还在其构造函数中调用了 setBackground(Color.RED)
和 setBounds(0, 0, 100, 100)
。
问题是,这个 JComponent
似乎根本没有被绘制出来。然而,如果我将 JComponent
所继承的类更改为 JPanel
,它就能正常工作。
这是否有影响?我想知道为什么会出现这种情况,似乎在我不需要其附加功能时继承 JPanel
只会带来不必要的开销。
谢谢您的时间。
英文:
I've added a JLayeredPane
to a JFrame
. To said pane i've added a JComponent
with overloaded paintComponent(Graphics g)
method, which calls super.paintComponent(g)
among other things. The JComponent
also has setBackground(Color.RED)
and setBounds(0, 0, 100, 100)
in its constructor.
The problem is, the JComponent
isn't being drawn at all it seems. However, if i change the class being extended by the JComponent
to JPanel
, it works just fine.
Does it matter at all? I would like to know why it works this way, it seems like extending JPanel
when i don't care for its additions is just unnecessary overhead.
Thanks for your time.
答案1
得分: 1
JComponent还可以使用setBackground(Color.RED)。
单独这样做不会有任何效果。
JComponent没有默认的绘制代码,因此调用super.paintComponent()不会导致任何背景被绘制。
如果你想绘制背景,你需要添加自己的自定义绘制代码:
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
英文:
> The JComponent also has setBackground(Color.RED)
On its own that will do nothing.
A JComponent has no default painting code, so invoking super.paintComponent() will NOT cause any background to be painted.
If you want to paint the background you need to add your own custom painting code:
g.seColor( getBackground() );
g.fillRect(0, 0, getWidth(), getHeight());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论