Overclock.net banner

Java- Button

292 Views 0 Replies 1 Participant Last post by  swim_fan08
I would appreciate it if I got help, as this assignment is due soon. My problem is that when the button is clicked, its suppose to change the color of the traffic light. My teacher said that I use 1 for red, 2 for yellow, and 3 for green and if statements to change the color, but I am not too sure how to do this since I am new to java.

Code:
Code:
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);
}
}
Code:
Code:
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TrafficLightPanel extends JPanel
{

private int state;
private JButton status;
private JLabel label;

//--------------------------------------------
//Constructor:Creates three circle objects
//------------------------------------------

public TrafficLightPanel()
{

//----------------------------------------------
//Constructor: Sets up the GUI
//----------------------------------------------

status = new JButton ("State");
status.addActionListener (new ButtonListener());

label = new JLabel ();

add(status);
add (label);

setPreferredSize (new Dimension (300,200));
setBackground (Color.black);
}

//-------------------------------------------------------
//Represents a listener for button status (action) events
//--------------------------------------------------------
private class ButtonListener implements ActionListener
{

//---------------------------------------------------------------
//Updates the state of the traffic light when the button is pushed
//----------------------------------------------------------------
public void actionPerformed (ActionEvent event)
{
state++;

red=1;
yellow=2;
green=3;

status = new JButton("State");
repaint();

}
}

//-------------------------------------------------------------
//Draws this panel by requesting that each circle draw itself
//-------------------------------------------------------------

public void paintComponent (Graphics page)
{
  super.paintComponent(page);

  page.setColor(Color.red);
      page.fillOval(112, 60, 60,60);

      page.setColor(Color.yellow);
      page.fillOval(112, 60, 60,60);

      page.setColor(Color.green);
    page.fillOval(112, 60, 60,60);

page.setColor(Color.white);
page.drawString("Ready...Set...GO!!!",100,180);

}
}
See less See more
1 - 1 of 1 Posts
1 - 1 of 1 Posts
This is an older thread, you may not receive a response, and could be reviving an old thread. Please consider creating a new thread.
Top