Canvas vs. Panel
Solution 1
In general, if you're using Swing, you should only use Swing components. Mixing Swing and AWT components in the same GUI leads to strange results. So I would use a JPanel, or a raw JComponent.
Solution 2
Canvas
is an AWT object; JPanel
is a lightweight Java Swing object. If you have a Java Swing GUI, I'd strongly recommend using JPanel
.
Here's a good link on JPanel:
In the simplest case, you use a
JPanel
exactly the same way as you would aPanel
. Allocate it, drop components in it, then add theJPanel
to someContainer
. However,JPanel
also acts as a replacement forCanvas
(there is noJCanvas
)...
Solution 3
Or you can use a JLabel
if you want display static images like icons.
BufferedImage image=
new BufferedImage(100, 50, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
// draw
g2.draw(new Ellipse2D.Double(x, y, rectwidth,rectheight));
g2.fill (new Ellipse2D.Double(0, 0, 100, 50));
JLabel label = new JLabel(new ImageIcon( image ));
Anonymous181
Updated on June 24, 2022Comments
-
Anonymous181 almost 2 years
If I want to display ellipses and rectangles on a screen, should I use a canvas or a JPanel?
What is the difference? When do I use each?
-
Andrew Thompson almost 12 yearsDon't forget to
dispose()
of anyGraphics
instance you explicitly create. -
Admin almost 4 yearsBroken link, I would have liked to read it since this post is 8 years old
-
paulsm4 almost 4 yearsHere is another, different link to the same chapter: Core Web Programming, Marty Hall, Larry Brown