3

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?

Anonymous181
  • 1,805
  • 5
  • 24
  • 27

4 Answers4

5

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)...

Andrew Thompson
  • 166,747
  • 40
  • 210
  • 420
paulsm4
  • 107,438
  • 16
  • 129
  • 179
  • Broken link, I would have liked to read it since this post is 8 years old –  Jul 03 '20 at 16:21
  • 1
    Here is another, different link to the same chapter: [Core Web Programming, Marty Hall, Larry Brown](https://books.google.com/books?id=q45_UDI77PoC&pg=PA585&lpg=PA585&dq=However,+JPanel+also+acts+as+a+replacement+for+Canvas+(there+is+no+JCanvas)...&source=bl&ots=RVHQqXgzW8&sig=ACfU3U1xjQaJJ9DnnnKMJLkf8r0nfEXcag&hl=en&sa=X&ved=2ahUKEwig4aH5_7PqAhVEUKwKHaBhBAAQ6AEwAHoECAoQAQ#v=onepage&q=However%2C%20JPanel%20also%20acts%20as%20a%20replacement%20for%20Canvas%20(there%20is%20no%20JCanvas)...&f=false) – paulsm4 Jul 04 '20 at 16:22
3

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.

JB Nizet
  • 657,433
  • 87
  • 1,179
  • 1,226
1

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 ));
Paul Vargas
  • 40,346
  • 15
  • 98
  • 144
0

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.