How to create a Graphics2D instance?

徘徊边缘 提交于 2020-01-03 08:57:33

问题


What's the easiest way in Java SE 7 to obtain an instance just to plot a few points for debugging? Desktop environment.


回答1:


You could use a BufferedImage:

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics2D = image.createGraphics();



回答2:


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.

@Override
public void paintComponent(Graphics g) {
   super.paintComponent(g);
   Graphics2D g2d = (Graphics2D)g;
   ...
}



回答3:


You should probably just create a JPanel and paint on it.

public class MyPanel extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        .... // my painting
    }
}


来源:https://stackoverflow.com/questions/16532704/how-to-create-a-graphics2d-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!