Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing in Java using Canvas

I want to draw in Java's Canvas but can't get it work because I don't know what I'm doing. Here's my simple code:

import javax.swing.JFrame;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Color;

public class Program
{
    public static void main(String[] args)
    {
        JFrame frmMain = new JFrame();
        frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmMain.setSize(400, 400);

        Canvas cnvs = new Canvas();
        cnvs.setSize(400, 400);

        frmMain.add(cnvs);
        frmMain.setVisible(true);

        Graphics g = cnvs.getGraphics();
        g.setColor(new Color(255, 0, 0));
        g.drawString("Hello", 200, 200);
    }
}

Nothing appears on the window.

Am I wrong to think that Canvas is a paper and Graphics is my Pencil? Is that how it works?

like image 830
dpp Avatar asked Mar 08 '12 03:03

dpp


People also ask

What is a canvas in Java?

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.

Can you draw using Java?

The Java library includes a simple package for drawing 2D graphics, called java. awt . AWT stands for “Abstract Window Toolkit”. We are only going to scratch the surface of graphics programming; you can read more about it in the Java tutorials at https://docs.oracle.com/javase/tutorial/2d/.


2 Answers

Suggestions:

  • Don't use Canvas as you shouldn't mix AWT with Swing components unnecessarily.
  • Instead use a JPanel or JComponent.
  • Don't get your Graphics object by calling getGraphics() on a component as the Graphics object obtained will be transient.
  • Draw in the JPanel's paintComponent() method.
  • All this is well explained in several tutorials that are easily found. Why not read them first before trying to guess at this stuff?

Key tutorial links:

  • Basic Tutorial: Lesson: Performing Custom Painting
  • More advanced information: Painting in AWT and Swing
like image 51
Hovercraft Full Of Eels Avatar answered Sep 18 '22 21:09

Hovercraft Full Of Eels


You've got to override your Canvas's paint(Graphics g) method and perform your drawing there. See the paint() documentation.

As it states, the default operation is to clear the canvas, so your call to the canvas' graphics object doesn't perform as you would expect.

like image 32
Thorn G Avatar answered Sep 19 '22 21:09

Thorn G