java 如何创建 Graphics2D 实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16532704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a Graphics2D instance?
提问by necromancer
What's the easiest way in Java SE 7to obtain an instance just to plot a few points for debugging? Desktop environment.
在Java SE 7中获取实例以绘制几个调试点的最简单方法是什么?桌面环境。
回答by BLuFeNiX
You could use a BufferedImage
:
你可以使用一个BufferedImage
:
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics2D = image.createGraphics();
回答by Reimeus
The easiest and safest way is to use to cast the Graphics
reference in paintComponent
and cast it as needed. That way the Object
is correctly initialized. This reference can be passed to other custom painting methods as required.
最简单和最安全的方法是使用来转换Graphics
引用paintComponent
并根据需要进行转换。这样Object
就正确初始化了。可以根据需要将此引用传递给其他自定义绘制方法。
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
...
}
回答by greedybuddha
You should probably just create a JPanel and paint on it.
您可能应该创建一个 JPanel 并在其上绘画。
public class MyPanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
.... // my painting
}
}