Design and implement an application that draws a traffic light and uses a push button to change the state of the light. Derive the drawing surface from the JPanel class and use another panel to organize the drawing surface and the button.
I understand well enough how to make buttons and listeners (i think) but the actual drawing of the circles for the light is not working out.
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;
public class TrafficLight
{
//-------------------------------------
//Creates the main program frame
//-------------------------------------
public static void main (String[] args)
{
JFrame frame=new JFrame("Traffic Light");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
TrafficLightPanel panel = new TrafficLightPanel();
frame.getContentPane().add(new TrafficLightPanel());
frame.pack();
frame.setVisible(true);
}
}
//************************************************************
// Victoria Showalter Lab 6a
// Creates a traffic light.
//************************************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TrafficLightPanel extends JPanel
{
private int count;
private JButton status;
private JLabel label;
//--------------------------------------------------------
// Constructor: Sets up the GUI
//--------------------------------------------------------
public TrafficLightPanel ()
{
int red = 0;
int yellow = 1;
int green = 2;
status = new JButton ("Change!");
status.addActionListener (new ButtonListener());
label = new JLabel ("Traffic");
add (status);
add (label);
setPreferredSize (new Dimension (300,200));
setBackground (Color.black);
}
//--------------------------------------------------------
// Represents a new listener for button push.
//--------------------------------------------------------
private class ButtonListener implements ActionListener
{
//----------------------------------------------------
// Changes the color of the traffic light when the
// button is pushed.
//----------------------------------------------------
public void actionPerformed (ActionEvent event)
{
count++;
count = count % 3; // take the remainder of count/3, yielding 0, 1 or 2.
}
//--------------------------------------------------------
// Draws traffic light
//--------------------------------------------------------
public void paintComponent (Graphics page)
{
TrafficLightPanel.super.paintComponent (page);
if (count == 0)
{
page.setColor(Color.red);
page.fillOval (20, 30, 50, 65);
}
if (count == 1)
{
page.setColor(Color.yellow);
page.fillOval (20, 30, 50, 65);
}
if (count == 2)
{
page.setColor(Color.green);
page.fillOval (20, 30, 50, 65);
}
page.setColor(Color.white);
page.drawString("Ready...Set...GO!!!",10,180);
}
}
}
How do I physically make the traffic light? I have no errors thusfar and it compiles, but only displays a button that says "Change!" on a black screen. Please and thank you


Sign In
Create Account

Back to top









