The Java Programming Language

CanvasBoard! Example Program


Click below to go directly to a specific section:
Description | Source Code | Sample Run | Program Notes


 

Description

This program demonstrates and power of Java graphics along with their ease of use.


 

Source Code

import java.awt.*;
import java.awt.event.*;
import java.applet.*;


public class canvasboard extends Applet implements 
	MouseMotionListener, ItemListener {

	Canvas picture;
	Point spot;
	Choice Colors = null;

	public void init() {
		setLayout(new BorderLayout());
		
		//add canvas
		picture = new Canvas();
		addMouseMotionListener(this);
		setBackground(Color.black);

		//adds canvas to north region
		add("North", picture);
		
			
		//add color choices for foreground
		Colors = new Choice();
		Colors.addItem("white");
		Colors.addItem("gray");
		Colors.addItem("red");
		Colors.addItem("green");
		Colors.addItem("blue");
		Colors.addItem("yellow");
		Colors.addItem("magenta");
		Colors.addItem("cyan");
		Colors.addItem("pink");
		Colors.addItem("orange");
		Colors.addItemListener(this);
		add("West", Colors);
	}

	public void update(Graphics g) {
		// wont clear screen when mouse moves.
		paint(g);
	}
	
	public void mouseDragged(MouseEvent e) {
		spot = e.getPoint();
		repaint();
	}

	public void mouseMoved(MouseEvent e) {
		//must be implemented
	}

	public void itemStateChanged(ItemEvent e) {
		ItemSelectable is = e.getItemSelectable();
		String s = is.getSelectedObjects() [0].toString();
		
		if ("white".equals(s))
			setForeground(Color.white);
		else if ("gray".equals(s))
			setForeground(Color.gray);
		else if ("red".equals(s))
			setForeground(Color.red);
		else if ("green".equals(s))
			setForeground(Color.green);
		else if ("blue".equals(s))
			setForeground(Color.blue);
		else if ("yellow".equals(s))
			setForeground(Color.yellow);
		else if("magenta".equals(s))
			setForeground(Color.magenta);
		else if("cyan".equals(s))
			setForeground(Color.cyan);
		else if("pink".equals(s))
			setForeground(Color.pink);
		else if("orange".equals(s))
			setForeground(Color.orange);
	
		repaint();
	}
				
	public void paint(Graphics g) {
		if (spot !=null)
			g.fillOval(spot.x - 2, spot.y - 2, 4, 4);
	}
			

		
}

Click here to download a zip file containing the source code,class file, and html tags.


 

Sample Run Coose a color and start drawing, you may change colors at anytime, to clear the screen hit your browsers refresh button


 


Program Notes

This program was compiled and run using the Java Developers Kit, Version 1.2.1 for Win32 on x86 from Sun Microsystems running under Windows 98.


[Back] [Home]

 

Last modified: 09:55 PM on 11/24/1999