Drawing java with canvas

I want to draw Java canvas, but I can't make it work because I don't know what I'm doing This is 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));
        g.drawString("Hello",200,200);
    }
}

Nothing appears in the window

I was wrong to think that canvas is paper and graphics are my pencil? How does this work?

Solution

Recommendations:

>Do not use canvas because you should not unnecessarily mix AWT and swing components. > Instead, use JPanel or JComponent. > Do not get graphics objects by calling getgraphics () on the component, because the obtained graphics objects will be temporary. > Draw the paintcomponent() method of JPanel. > All of this is easily explained in several tutorials Why not try these things first?

Main tutorial links:

>Basic tutorial: Lesson: performing custom painting > more advanced information: painting in AWT and swing

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>