SirTrashyton
SirTrashyton

Reputation: 173

Drawing on Canvas without extending it?

In order to draw images and or shapes in my JFrame, I use a very common method that works.

I use a class that extends canvss, make my own custom JFrame object then add my own class (which extends camvas). Then, I override the 'paint' method in order to paint on the canvas.

Basicly, here is an example: http://pastebin.com/KhZudT3r

This whole process works perfectly, but I was wondering if there's a way to draw on a jframe (perferebly a canvas) without having to extend the canvas class?

Thanks,

Jake

Upvotes: 0

Views: 578

Answers (1)

Braj
Braj

Reputation: 46841

Try with JPanel and override paintComponent() method for your custom painting.

  • Don't forget to call super.paintComponent(g) in overridden method.

  • Never draw directly on JFrame itself instead draw on JPanel and then add it into JFrame

Sample code:

JPanel panel = new JPanel() {
    @Override
    public void paintComponent(Graphics g) {
      super.paintComponent(g);

      //your custom drawing here
    }
};

Upvotes: 1

Related Questions