|
| 1. Introduction | |
| 2. Programme |
Here I give an example (taken from Holmes, B. (1998)) that brings together much of the material covereded in the foregoing WWW pages. The result is a simple drawing prohram.
Table 1 gives the source code and Figure 1 some sample output.
// Draw program
// Frans Coenen
// University of Liverpool, Dept of Comp. Sci.
// Wednesday, 10 January 2001
import java.awt.*;
import java.awt.event.*;
class Draw extends Frame implements
ActionListener, // menu item
ItemListener, // radio buttons
MouseListener, // mouse clicks
MouseMotionListener, // mouse movement
WindowListener { // Window
/* -------------------------------------------------------- */
/* */
/* FIELDS */
/* */
/* -------------------------------------------------------- */
static final int WIDTH = 800; // Sketch pad width
static final int HEIGHT = 600; // Sketch pad height
int upperLeftX, upperLeftY; // Rectangle upper left corner coords.
int width, height; // Rectangle size
int x1, y1, x2, y2; // Point coords.
boolean fillFlag = false;
boolean eraseFlag = false;
String drawColor = new String("black");
String drawShape = new String("line");
// Help
String helpText = "Draw allows you to sketch different plane shapes over a " +
"predefined area.\n" + "A shape may be eother filled or in outline, " +
"and in one of eight different colours.\n\n" + "The position of the " +
"mouse on the screen is recorded in the bottom left-hand corner of the " +
"drawing area. The choice of colour and shape are disoplayed also in the " +
"left-habnd corner of the drawing area.\n\n" + "The size of a shape is " +
"determined by the mouse being dragged to the final position and " +
"released. The first click of the mouse will generate a reference dot on " +
"the screen. This dot will disapear after the mouse button is released.\n\n" +
"Both the square and the circle only use the distance measured along the " +
"horizontal axis when determining the size of a shape.\n\n" + "Upon " +
"selecting erase, press the mouse button, and move the mouse over the " +
"area to be erased. releasing the mouse button will deactivate erasure.\n\n" +
"To erase this text area choose clearpad from the TOOLS menu.\n\n";
// Components
TextField color = new TextField();
TextField shape = new TextField();
TextField position = new TextField();
CheckboxGroup fillOutline = new CheckboxGroup();
TextArea info = new TextArea(helpText,0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
Frame about = new Frame("About Frans draw");
// Menues
String[] colorNames = {"black","blue","cyan","gray","green","magenta","red","white","yellow"};
String[] shapeNames = {"line","square","rectangle","circle","ellipse"};
String[] toolNames = {"erase","clearpad"};
String[] helpNames = {"information","about"};
/* -------------------------------------------------------- */
/* */
/* CONSTRUCTORS */
/* */
/* -------------------------------------------------------- */
public Draw(String heading) {
super(heading);
setBackground(Color.yellow);
setLayout(null);
/* Initialise components */
initialiseTextFields();
initializeMenuComponents();
initializeRadioButtons();
addWindowListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}
/* -------------------------------------------------------- */
/* */
/* METHODS */
/* */
/* -------------------------------------------------------- */
/* Initialise Text Fields */
private void initialiseTextFields() {
// Add text field to show colour of figure
color.setLocation(5,490);
color.setSize(80,30);
color.setBackground(Color.white);
color.setText(drawColor);
add(color);
// Add text field to show shape of figure
shape.setLocation(5,525);
shape.setSize(80,30);
shape.setBackground(Color.white);
shape.setText(drawShape);
add(shape);
// Add text field to show position of mouse
position.setLocation(5,560);
position.setSize(80,30);
position.setBackground(Color.white);
add(position);
// Set up text field for help
info.setLocation(150,250);
info.setSize(500,100);
info.setBackground(Color.white);
info.setEditable(false);
}
/* Initialize Menu Components */
private void initializeMenuComponents() {
// Create menu bar
MenuBar bar = new MenuBar();
// Add colurs menu
Menu colors = new Menu("COLORS");
for(int index=0;index < colorNames.length;index++)
colors.add(colorNames[index]);
bar.add(colors);
colors.addActionListener(this);
// Add shapes menu
Menu shapes = new Menu("SHAPES");
for(int index=0;index < shapeNames.length;index++)
shapes.add(shapeNames[index]);
bar.add(shapes);
shapes.addActionListener(this);
// Add tools menu
Menu tools = new Menu("TOOLS");
for(int index=0;index < toolNames.length;index++)
tools.add(toolNames[index]);
bar.add(tools);
tools.addActionListener(this);
// Add help menu
Menu help = new Menu("HELP");
for(int index=0;index < helpNames.length;index++)
help.add(helpNames[index]);
bar.add(help);
help.addActionListener(this);
// Set up menu bar
setMenuBar(bar);
}
/* Initilalise Radio Buttons */
private void initializeRadioButtons() {
// Define checkbox
Checkbox fill = new Checkbox("fill",fillOutline,false);
Checkbox outline = new Checkbox("outline",fillOutline,true);
// Fill buttom
fill.setLocation(5,455);
fill.setSize(80,30);
add(fill);
fill.addItemListener(this);
// Outline button
outline.setLocation(5,420);
outline.setSize(80,30);
add(outline);
outline.addItemListener(this);
}
/* -------------------------------------------------------- */
/* */
/* LISTENERS */
/* */
/* -------------------------------------------------------- */
// ----------------------- ACTION LISTENERS -------------------
/* Action performed. Detects which item has been selected from a menu */
public void actionPerformed(ActionEvent event) {
Graphics g = getGraphics();
String source = event.getActionCommand();
// Identify chosen colour if any
for (int index=0;index < colorNames.length;index++) {
if (source.equals(colorNames[index])) {
drawColor = colorNames[index];
color.setText(drawColor);
return;
}
}
// Identify chosen shape if any
for (int index=0;index < shapeNames.length;index++) {
if (source.equals(shapeNames[index])) {
drawShape = shapeNames[index];
shape.setText(drawShape);
return;
}
}
// Identify chosen tools if any
if (source.equals("erase")) {
eraseFlag= true;
return;
}
else {
if (source.equals("clearpad")) {
remove(info);
g.clearRect(0,0,800,600);
return;
}
}
// Identify chosen help
if (source.equals("information")) {
add(info);
return;
}
else displayAboutWindow(about);
}
/* Dispaly About Window: Shows iformation aboutb Draw programme in
separate window */
private void displayAboutWindow(Frame about) {
about.setLocation(300,300);
about.setSize(350,160);
about.setBackground(Color.cyan);
about.setFont(new Font("Serif",Font.ITALIC,14));
about.setLayout(new FlowLayout(FlowLayout.LEFT));
about.add(new Label("Author: Frans Coenen"));
about.add(new Label("Title: Draw"));
about.add(new Label("Location: University of Liverpool, Dept of Comp. Sci."));
about.add(new Label("Date: Wednesday, 10 January 2001"));
about.add(new Label("Based on original idea by Barry Holmes"));
about.setVisible(true);
about.addWindowListener(this);
}
// ----------------------- ITEM LISTENERS -------------------
/* Item state changed: detect radio button presses. */
public void itemStateChanged(ItemEvent event) {
if (event.getItem() == "fill") fillFlag=true;
else if (event.getItem() == "outline") fillFlag=false;
}
// ---------------------- MOUSE LISTENERS -------------------
/* Blank mouse listener methods */
public void mouseClicked(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
/* Mouse pressed: Get start coordinates */
public void mousePressed(MouseEvent event) {
// Cannot draw if erase flag switched on.
if (eraseFlag) return;
// Else set parameters to 0 and proceed
upperLeftX=0;
upperLeftY=0;
width=0;
height=0;
x1=event.getX();
y1=event.getY();
Graphics g = getGraphics();
// Display start point
g.drawString(".",x1,y1);
displayMouseCoordinates(x1,y1);
}
public void mouseReleased(MouseEvent event) {
Graphics g = getGraphics();
// Get and display mouse coordinates
x2=event.getX();
y2=event.getY();
displayMouseCoordinates(x2,y2);
// If erase flag set to true reset to false
if (eraseFlag) {
eraseFlag = false;
return;
}
// Else draw shape
selectColor(g);
if (drawShape.equals("line")) g.drawLine(x1,y1,x2,y2);
else drawClosedShape(drawShape,g);
// Remove reference point
g.setColor(Color.yellow);
g.drawString(".",x1,y1);
g.setColor(Color.black);
}
/* Display Mouse Coordinates */
private void displayMouseCoordinates(int x, int y) {
position.setText("[" + String.valueOf(x) + "," + String.valueOf(y) + "]");
}
/* Select colour */
private void selectColor(Graphics g) {
for (int index=0;index < colorNames.length;index++) {
if (drawColor.equals(colorNames[index])) {
switch(index) {
case 0: g.setColor(Color.black);break;
case 1: g.setColor(Color.blue);break;
case 2: g.setColor(Color.cyan);break;
case 3: g.setColor(Color.gray);break;
case 4: g.setColor(Color.green);break;
case 5: g.setColor(Color.magenta);break;
case 6: g.setColor(Color.red);break;
case 7: g.setColor(Color.white);break;
default: g.setColor(Color.yellow);
}
}
}
}
/* Draw closed shape */
private void drawClosedShape(String shape,Graphics g) {
// Calculate correct parameters for shape
upperLeftX = Math.min(x1,x2);
upperLeftY = Math.min(y1,y2);
width = Math.abs(x1-x2);
height = Math.abs(y1-y2);
// Draw appropriate shape
if (shape.equals("square")) {
if (fillFlag) g.fillRect(upperLeftX,upperLeftY,width,width);
else g.drawRect(upperLeftX,upperLeftY,width,width);
}
else {
if (shape.equals("rectangle")) {
if (fillFlag) g.fillRect(upperLeftX,upperLeftY,width,height);
else g.drawRect(upperLeftX,upperLeftY,width,height);
}
else {
if (shape.equals("circle")) {
if (fillFlag) g.fillOval(upperLeftX,upperLeftY,width,width);
else g.drawOval(upperLeftX,upperLeftY,width,width);
}
else {
if (fillFlag) g.fillOval(upperLeftX,upperLeftY,width,height);
else g.drawOval(upperLeftX,upperLeftY,width,height);
}
}
}
}
// ----------------------- MOUSE MOVEMENT --------------------
/* Mouse moved */
public void mouseMoved(MouseEvent event) {
displayMouseCoordinates(event.getX(),event.getY());
}
/* Mouse dragged */
public void mouseDragged(MouseEvent event) {
Graphics g = getGraphics();
x2=event.getX();
y2=event.getY();
if (eraseFlag) g.clearRect(x2,y2,5,5);
displayMouseCoordinates(x1,y1);
}
// ---------------------- WINDOW LISTENERS -------------------
/* Blank methods for window listener */
public void windowClosed(WindowEvent event) {}
public void windowDeiconified(WindowEvent event) {}
public void windowIconified(WindowEvent event) {}
public void windowActivated(WindowEvent event) {}
public void windowDeactivated(WindowEvent event) {}
public void windowOpened(WindowEvent event) {}
/* Window Closing */
public void windowClosing(WindowEvent event) {
if (event.getWindow() == about) {
about.dispose();
return;
}
else System.exit(0);
}
}
/* --------------------------------------------------------------- */
/* */
/* DRAW APP */
/* */
/* --------------------------------------------------------------- */
class DrawApp {
/* Main method */
public static void main(String[] args) {
Draw screen = new Draw("Frans draw");
screen.setSize(Draw.WIDTH,Draw.HEIGHT);
screen.setVisible(true);
}
}
|
Table 1:Drawing programme
Figure 21: Example output from code presented in Table 1
Created and maintained by Frans Coenen. Last updated 04 February 2002