JComponent未在JLayeredPane上绘制,而JPanel却有。

huangapple go评论69阅读模式
英文:

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());

huangapple
  • 本文由 发表于 2020年9月25日 08:14:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/64056059.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定