gpt4 book ai didi

Java Swing-JPanel 与 JComponent

转载 作者:搜寻专家 更新时间:2023-10-31 19:55:48 24 4
gpt4 key购买 nike

我正在玩弄 Java Swing,当涉及到 JPanel 和 JComponent 时,我真的很困惑。根据 CoreJava 第 1 卷(cay horstmann):

Instead of extending JComponent, some programmers prefer to extend the JPanel class. A JPanel is intended to be a container that can contain other components, but it is also possible to paint on it. There is just one difference. A panel is opaque, which means that it is responsible for painting all pixels within its bounds. The easiest way to achieve that is to paint the panel with the background color, by calling super.paintComponent in the paintComponent method of each panel subclass:

class NotHelloWorldPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
. . . // code for drawing will go here
}
}

我知道什么是不透明。他所说的“面板是不透明的……负责绘制其边界内的所有像素”是什么意思?如果我没看错的话,它说面板将在其边界内绘制自己的区域。JComponent 不也这样做吗?

底线是我看不出 JPanel 和 JComponent 之间的区别。有没有我可以真正看到的简单示例?

感谢任何帮助

最佳答案

JComponent 不需要绘制其绑定(bind)的所有像素。它可能会留下一些透明的部分,以便您可以看到它后面的组件。

需要一个 JPanel 来绘制所有像素。

当然,如果您在任何一种情况下都不调用 super.paintComponent(..) 方法,它们将或多或少是等价的,因为您随后会抛出保证JPanel 将绘制整个面板。

简而言之,区别在于已经存在的方法(即绘制组件)。

编辑:

使用 JComponent 实现的球类示例如下所示:

(这不适用于 JPanel,因为 JPanel 是不透明的,并且球将具有方形背景。您不能调用 super.paintComponent,但作为一般规则,您始终应该,或者你破坏了组件的真正含义。如果我将 JPanel 传递给某个东西,他们希望它是一个 JPanel,而不是一个被黑客攻击后表现得像 JComponent 的 JPanel)

public class Ball extends JComponent
{
public Ball(int x, int y, int diameter)
{
super();
this.setLocation(x, y);
this.setSize(diameter, diameter);
}

public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
g.fillOval(0, 0, width, height);
}
}

关于Java Swing-JPanel 与 JComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19122416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com