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?
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 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/.
Suggestions:
getGraphics()
on a component as the Graphics object obtained will be transient.paintComponent()
method.Key tutorial links:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With