How to make canvas with Swing?

mccrank picture mccrank · Apr 22, 2009 · Viewed 60.9k times · Source

I'm trying to make a paint editor with Java in which I have a toolbar with the objects that I would like to paste in the canvas. I'm using Swing components to make the GUI, but when I looked for the way of making the canvas, I only found the class canvas from AWT.

Is there any way to make something similar to canvas with Swing? (for example, JPanel?) I have read that using the class canvas from AWT with a GUI made with swing won't work correctly, is that true?

Answer

jjnguy picture jjnguy · Apr 22, 2009

In order to make a custom 'Canvas' in swing you usually write a subclass of a JPanel. Then, you must overwrite the protected paintComponent(Graphics g) method of JPanel.

In the paint method, you can call methods on the Graphics object to actually draw on the JPanel.

As always, the Java Tutorials have a great reference on this to get you started.