Draw2

Main.java  [download]

/*
 * Drawing in a Canvas
 * RIGHT WAY -- Does drawing in a callback
 */

import java.awt.*; //*3 Can import whole packages this way
import javax.swing.*; //*3

public class Main extends JFrame {
    public static void main (String [] args) {
	java.awt.EventQueue.invokeLater (new Runnable() {
            public void run() {
		new Main ();
            }
        });
    }

    public Main () {
	// Window setup
	setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
	setSize (300, 300);
	Container content = getContentPane();
	
	// Put a Canvas in
	MyCanvas canvas = new MyCanvas ();
	content.add (canvas);
    
	// Show the window
	setVisible (true); //*2 Automatically triggers an initial first "repaint"

	// No drawing here, do it in MyCanvas callback
	//*1 No drawing here
    }
}

MyCanvas.java  [download]

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class MyCanvas extends JPanel {
    // This is the draw callback
    public void paintComponent (Graphics g) { //*1 Right way, draw in the callback
	super.paintComponent(g); //*3 Supposed to chain to superclass, which clears background first
	g.drawLine (50, 50, 100, 50); //*2 Draw on the "g" object
    }
}