Here is my code:
TrafiicLight Class
import javax.swing.JFrame; public class TrafficLight { 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(panel); frame.pack(); frame.setVisible(true); } }
TrafficLightPanel Class
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TrafficLightPanel extends JPanel{ private JLabel changeColor; private JButton red, green, yellow; private Circle light; public TrafficLightPanel(){ light = new Circle(20, Color.red, 150, 70); changeColor = new JLabel("Change color to: "); red = new JButton("red"); red.addActionListener(new RedButtonListener()); green = new JButton("green"); green.addActionListener(new GreenButtonListener()); yellow = new JButton("yellow"); yellow.addActionListener(new YellowButtonListener()); add(changeColor); add(red); add(yellow); add(green); setPreferredSize (new Dimension(300, 100)); setBackground (Color.gray); } public void paintComponent(Graphics page){ super.paintComponent(page); page.setColor(Color.black); page.fillRect(150, 50, 20, 40); /*page.setColor(Color.red); page.fillOval(150, 60, 20, 20);*/ light.draw(page); } private class RedButtonListener implements ActionListener{ public void actionPerformed(ActionEvent event){ light.setColor(Color.red); System.out.println(light.getColor()); } } private class YellowButtonListener implements ActionListener{ public void actionPerformed(ActionEvent event){ light.setColor(Color.yellow); System.out.println(light.getColor()); } } private class GreenButtonListener implements ActionListener{ public void actionPerformed(ActionEvent event){ light.setColor(Color.green); } } }
Circle Class
import java.awt.*; public class Circle { private int diameter, x, y; private Color color; public Circle (int size, Color shade, int upperX, int upperY){ diameter = size; color = shade; x = upperX; y = upperY; } public void draw (Graphics page){ page.setColor (color); page.fillOval (x, y, diameter, diameter); } public void setDiameter (int size){ diameter = size; } public void setColor (Color shade) { color = shade; } public void setX (int upperX){ x = upperX; } public void setY (int upperY){ y = upperY; } public int getDiameter (){ return diameter; } public Color getColor (){ return color; } public int getX (){ return x; } public int getY (){ return y; } }
thanks a lot in advance for the help!!