necromancer
necromancer

Reputation: 24641

How to create a Graphics2D instance?

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

Upvotes: 11

Views: 23366

Answers (3)

Reimeus
Reimeus

Reputation: 159844

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;
   ...
}

Upvotes: 6

BLuFeNiX
BLuFeNiX

Reputation: 2594

You could use a BufferedImage:

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

Upvotes: 19

greedybuddha
greedybuddha

Reputation: 7507

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
    }
}

Upvotes: 3

Related Questions