The Java Programming Language

Hello world! Example Program


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


Description

This program provides an applet in which you can draw on a canvas.  Different colors can be chosen but each time a color is chosen the board is erased.


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);

}

}


Sample Run


Program Notes

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


[Back] [Home]


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