Traffic Light

Compiled By Unknown - No Comments
This sample code shows you how to easily draw Shapes on the screen, and also to determine if a mouse click falls within a given Shape. Download the following code, and get it to compile. Files Needed TrafficLight.java What You Should Do on Your Own Assignments turned in without these things will receive no credit. Right now, there are three ellipses defined, but only two of them are drawn. Draw the third ellipse on the screen, in green. Add code so that a message is displayed when the yellow or green circles are clicked. Use following code to compile TrafficLight.java
 import java.awt.*;  
import javax.swing.JFrame;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.geom.*;
public class TrafficLight extends Canvas implements MouseListener
{
private String message;
private Shape circle1, circle2, circle3;
public TrafficLight()
{
addMouseListener(this);
message = "Click on one of the circles!";
circle1 = new Ellipse2D.Double(500, 50,150,150);
circle2 = new Ellipse2D.Double(500,210,150,150);
circle3 = new Ellipse2D.Double(500,370,150,150);
}
public void paint( Graphics g )
{
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.black);
g2.drawString(message, 50, 100);
g2.setColor(Color.red);
g2.fill(circle1);
g2.setColor(Color.yellow);
g2.fill(circle2);
}
public void mouseClicked( MouseEvent evt )
{
if ( circle1.contains( evt.getPoint() ) )
message = "You clicked on the red circle!";
else
message = "You clicked at (" + evt.getX() + "," + evt.getY() + ")";
repaint();
}
public void mousePressed( MouseEvent evt )
{
}
public void mouseReleased( MouseEvent evt )
{
}
public void mouseEntered( MouseEvent evt )
{
}
public void mouseExited( MouseEvent evt )
{
}
public static void main(String[] args)
{
JFrame win = new JFrame("Traffic Light");
win.setSize(1024,768);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.add( new TrafficLight() );
win.setVisible(true);
}
}

Tags:

No Comment to " Traffic Light "