[java] 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?

This question is related to java swing graphics canvas awt

The answer is


The following should work:

public static void main(String[] args)
{
    final String title = "Test Window";
    final int width = 1200;
    final int height = width / 16 * 9;

    //Creating the frame.
    JFrame frame = new JFrame(title);

    frame.setSize(width, height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setVisible(true);

    //Creating the canvas.
    Canvas canvas = new Canvas();

    canvas.setSize(width, height);
    canvas.setBackground(Color.BLACK);
    canvas.setVisible(true);
    canvas.setFocusable(false);


    //Putting it all together.
    frame.add(canvas);

    canvas.createBufferStrategy(3);

    boolean running = true;

    BufferStrategy bufferStrategy;
    Graphics graphics;

    while (running) {
        bufferStrategy = canvas.getBufferStrategy();
        graphics = bufferStrategy.getDrawGraphics();
        graphics.clearRect(0, 0, width, height);

        graphics.setColor(Color.GREEN);
        graphics.drawString("This is some text placed in the top left corner.", 5, 15);

        bufferStrategy.show();
        graphics.dispose();
    }
}

Why would the first way not work. Canvas object is created and the size is set and the grahpics are set. I always find this strange. Also if a class extends JComponent you can override the

paintComponent(){
  super...
}

and then shouldn't you be able to create and instance of the class inside of another class and then just call NewlycreateinstanceOfAnyClass.repaint();

I have tried this approach for some game programming I have been working and it doesn't seem to work the way I think that it should be.

Doug Hauf


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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to swing

Calling another method java GUI Read input from a JOptionPane.showInputDialog box Call japplet from jframe Java JTable getting the data of the selected row What does .pack() do? How to add row of data to Jtable from values received from jtextfield and comboboxes How can I check that JButton is pressed? If the isEnable() is not work? Load arrayList data into JTable How to draw a circle with given X and Y coordinates as the middle spot of the circle? Simplest way to set image as JPanel background

Examples related to graphics

How to play or open *.mp3 or *.wav sound file in c++ program? How to use graphics.h in codeblocks? How do I get the height and width of the Android Navigation Bar programmatically? How to Change Font Size in drawString Java How can I produce an effect similar to the iOS 7 blur view? Creating a blurring overlay view Saving images in Python at a very high quality Android: Background Image Size (in Pixel) which Support All Devices How to create a Rectangle object in Java using g.fillRect method Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

Examples related to canvas

How to make canvas responsive How to fill the whole canvas with specific color? Use HTML5 to resize an image before upload Convert canvas to PDF Scaling an image to fit on canvas Split string in JavaScript and detect line break Get distance between two points in canvas canvas.toDataURL() SecurityError Converting Chart.js canvas chart to image using .toDataUrl() results in blank image Chart.js canvas resize

Examples related to awt

How can I check that JButton is pressed? If the isEnable() is not work? How to Change Font Size in drawString Java Font.createFont(..) set color and size (java.awt.Font) Triangle Draw Method How to use KeyListener Drawing in Java using Canvas Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot? Create GUI using Eclipse (Java) Getting a HeadlessException: No X11 DISPLAY variable was set Setting background color for a JFrame