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?
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?
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
)...
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.
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 ));
That kind of depends on what you like, but, I would use JFrame, it directly creates a window, and you can draw onto it. Canvas has its advantages, it let's you write one less import, it also separates window stuff from canvas graphics stuff, but it has its the disadvantages of not having access to window. it depends on what you like and need.