gpt4 book ai didi

java - 在 JPanel 上绘画与在 JComponent 上绘画有什么好处?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:57:06 26 4
gpt4 key购买 nike

所以在最近的回答中,有人评论了这个(关于绘画):

"This is probably some kind of illness of 90% of Swing Programmers: When they make their own component, they always extend JPanel instead of JComponent. Why?"

我对编程还很陌生,所以我认为现在称自己为 Swing 程序员还为时过早,因为我还没有找到自己的定位。但是重写 JPanel 正是我被教导的方式。因此,我着手寻找评论者提出的“为什么?” 问题的答案。这些是我找到的一些答案。


Background painting is main difference. The JComponent class doesn't paint its background, so you have to paint the background in the overridden paintComponent method. In contrast, JPanel has an opaque background which can be painted by calling its paintComponennt method.


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:


If the opaque property is set to true ... then the Swing painting system does not have to waste time trying to paint behind the component, hence improves performance.


我认为最后一句话最能说明问题。但是除了不透明之外,还有其他有益的原因“90% 的 Swing 程序员都有这种病” 扩展 JPanel 而不是 JComponent 吗?

最佳答案

不透明度处理的差异并不是唯一的因素。

查看 JPanel 源代码会有所帮助,因为它只有约 100 行。

所有的构造函数最终都会调用这个构造函数。不透明度和双缓冲默认为 true。默认的 LayoutManager 是 Fl​​owLayout,您可能想要也可能不想要。

public JPanel(LayoutManager layout, boolean isDoubleBuffered) {
setLayout(layout);
setDoubleBuffered(isDoubleBuffered);
setUIProperty("opaque", Boolean.TRUE);
updateUI();
}

O'Reilly 的 Java Swing 第 2 版中的 Loy 等人建议为真正的自定义组件扩展 JComponent(第 1333 页),但也提到需要考虑 UI 委托(delegate)。 JPanel 处理它自己的具体 AccessibleContext,而扩展 JComponent 的类返回 null。

对于只读可视组件,我通常会扩展 JComponent,但对于交互式组件,我可能会三思而后行,因为需要额外考虑可访问性。

干杯,

关于java - 在 JPanel 上绘画与在 JComponent 上绘画有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20787800/

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