Canvas vs. Panel

17,392

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 a Panel. Allocate it, drop components in it, then add the JPanel to some Container. However, JPanel also acts as a replacement for Canvas (there is no JCanvas)...

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 ));
Share:
17,392
Anonymous181
Author by

Anonymous181

Updated on June 24, 2022

Comments

  • Anonymous181
    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
    Andrew Thompson almost 12 years
    Don't forget to dispose() of any Graphics instance you explicitly create.
  • Admin
    Admin almost 4 years
    Broken link, I would have liked to read it since this post is 8 years old
  • paulsm4
    paulsm4 almost 4 years
    Here is another, different link to the same chapter: Core Web Programming, Marty Hall, Larry Brown