本文介绍了Swing 自定义绘画:应该处理`Graphic` 对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当覆盖任何 JComponent 中的 public void paintComponent(Graphics g) 以执行该 JComponent 的自定义绘制时,Graphic 对象 g 被设置在画的末尾(以及为什么)?

public void paintComponent(Graphics g) {super.paintComponent(g);g.drawString("处置还是不处置?",10,20);//处理还是避免?g.dispose();}
解决方案

除非您的代码创建了 Graphics 对象,否则您不应处理 Graphics 对象.

JComponentpaint() 方法将创建一个Graphics 对象,并将其传递给每个组件的三个绘制方法.请参阅:深入了解绘画机制.>

当组件绘制完成时,paint() 方法将dispose() 这个临时Graphics 对象.在以下位置查看代码:https://github.com/openjdk/jdk/blob/master/src/java.desktop/share/classes/javax/swing/JComponent.java

如果你手动创建了一个 Graphics 对象,那么你应该处理它:

Graphics2D g2d = (Graphics2D)g.create();//做自定义绘画g2d.dispose();

通常,如果您打算通过向 Graphics 添加 AffineTransform 来更改绘画,则创建传递的 Graphics 对象的副本是个好主意.

When overriding public void paintComponent(Graphics g) in any JComponent to perform custom painting of that JComponent, should the Graphic object g be disposed at the end of the painting (and why)?

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawString("To dispose or not to dispose ? ",10,20);
    //dispose or avoid ?
    g.dispose();
}
解决方案

You should not dispose of the Graphics object unless your code creates the Graphics object.

The paint() method of JComponent will create a Graphics object and pass it to the three painting methods of each component.See: A Closer Look at the Painting Mechanisn.

The paint() method will then dispose() of this temporary Graphics object when painting of the component is finished. Check out the code at: https://github.com/openjdk/jdk/blob/master/src/java.desktop/share/classes/javax/swing/JComponent.java

If you manually create a Graphics object then you should dispose it:

Graphics2D g2d = (Graphics2D)g.create();

// do custom painting

g2d.dispose();

Typically it is a good idea to create a copy of the passed Graphics object if you intend to alter the painting by adding an AffineTransform, for example, to the Graphics.

这篇关于Swing 自定义绘画:应该处理`Graphic` 对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 19:51