Select a shape, color, and size (such as 200), then press the "Go" button.
(Code by C. Liu; comments by Thomas Albert)
The HTML source for this web page contains an applet:
<applet code="coloredShapes.class" width="500" height="300">
</applet>
// colorShapes.java is a Java 1.1 applet that allows the user to specify a
// shape, color, and size for an object that appears on the canvas when
// the user presses the "Go" button.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.math.*;
public class coloredShapes extends Applet{
Button b1; // For the "Go" button.
TextField tf; // For user to specify the size.
Choice shape,color;
Label label1,label2,label3; // Labels for shape, color, size.
myCanvas mc;
class myCanvas extends Canvas{ // Innerclass of coloredShapes.
int x;
// Declare the variable for the size.
public myCanvas()
// Constructor for the canvas that displays the shape.
{
}
public void paint(Graphics g)
{
// Get the size the user
types in the text field.
int x=Integer.parseInt(tf.getText());
int[] xcoord={x/2,x,0}; // Radius of circle uses x/2.
int[] ycoord={0,x,x};
if((color.getSelectedItem()).equals("Blue"))
g.setColor(Color.blue);
if((color.getSelectedItem()).equals("Green"))
g.setColor(Color.green);
if((color.getSelectedItem()).equals("Red"))
g.setColor(Color.red);
if((shape.getSelectedItem()).equals("Circle"))
g.fillOval(0, 0, x, x); // Start circle in top left.
if((shape.getSelectedItem()).equals("Triangle"))
g.fillPolygon(xcoord,ycoord,3);
if((shape.getSelectedItem()).equals("Square"))
g.fillRect(0, 0, x, x);
}
}
public void init(){ // The user
interface.
setLayout(new BorderLayout());
b1=new Button("Go");
tf=new TextField("0",7);
mc=new myCanvas();
shape=new Choice();
shape.add("Circle");
shape.add("Triangle");
shape.add("Square");
color=new Choice();
color.add("Blue");
color.add("Green");
color.add("Red");
label1=new Label("Shape");
label2=new Label("Color");
label3=new Label("Size");
Panel p=new Panel();
p.add(label1);
p.add(shape);
p.add(label2);
p.add(color);
p.add(label3);
p.add(tf);
p.add(b1);
add("Center",mc);
add("South",p);
b1.addActionListener(new B());
// Capture the event when user presses the "Go" button.
}
class B implements ActionListener{
// Innerclass of coloredShapes.
public void actionPerformed(ActionEvent e)
{
// When the user presses the "Go" button, repaint.
mc.repaint();
}
}
}
Last update: October 21, 2000