4

I've been searching many sources yet I still cannot find a decent explanation. Why should I use it, what is its' purpose and why does it differ from JPanels and such?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
beur_x
  • 169
  • 3
  • 11

3 Answers3

3

From my understanding, Canvas is just the AWT version of Swing's JComponent. You shouldn't use it directly, unless you're making a pure AWT app. You can find more info here.

Community
  • 1
  • 1
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
3

The speciality of Canvas is that, like Window, it can provide customized hardware-accelerated double-buffering and page-flipping. See BufferStrategy.

A canvas is for drawing on, basically. It also serves like a Panel for creating a custom AWT-based component, but unlike Panel it can't contain other components.

Boann
  • 48,794
  • 16
  • 117
  • 146
  • The question I linked to in my answer says you shouldn't use it in a Swing app. Do you agree w/ that? – Daniel Kaplan Jun 19 '13 at 18:04
  • 1
    @tieTYT: Canvas is probably less useful in a Swing app because Swing provides its own double buffering. (The Graphics object passed to paintComponent methods draws on to a BufferedImage which gets blitted to the screen later.) There is also the issue that Swing components can not layer in front of AWT components. Swing menus & tooltips will usually not be able to draw over the canvas either, but you can use JPopupMenu.setDefaultLightWeightPopupEnabled and ToolTipManager.setLightWeightPopupEnabled to fix this. Apart from that, you can certainly use Canvas in Swing if you want to. – Boann Jun 19 '13 at 18:20
  • @tieTYT See also [Mixing Heavyweight and Lightweight Components](http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html). – Andrew Thompson Jun 20 '13 at 16:05
0
public class Canvas
extends Component
implements Accessible

A Canvas component represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user. An application must subclass the Canvas class in order to get useful functionality such as creating a custom component. The paint method must be overridden in order to perform custom graphics on the canvas.

A canvas is for drawing on, basically. It also serves like a Panel for creating a custom AWT-based component, but unlike Panel it can't contain other components.

Shiva Saurabh
  • 1,281
  • 2
  • 25
  • 47
Deepak
  • 1
  • 2