import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class trafficLights extends JFrame {
private JRadioButton jrbRed, jrbYellow, jrbGreen;
private boolean jrbRedClicked = false;
private boolean jrbYellowClicked = false;
private boolean jrbGreenClicked = false;
public static void main(String[] args) {
trafficLights frame = new trafficLights();
frame.setTitle("Exercise 17_3");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
} // end of main
public trafficLights() {
JPanel jpRadioButtons = new JPanel();
jpRadioButtons.setLayout(new FlowLayout());
jpRadioButtons.add(jrbRed = new JRadioButton("Red"));
jpRadioButtons.add(jrbYellow = new JRadioButton("Yellow"));
jpRadioButtons.add(jrbGreen = new JRadioButton("Green"));
add(jpRadioButtons, BorderLayout.SOUTH);
JPanel drawLight = new JPanel();
drawLight.setLayout(new BorderLayout());
add(drawLight, BorderLayout.CENTER);
drawLight.add(jpRadioButtons, BorderLayout.SOUTH);
//keyboard mnemonics
jrbRed.setMnemonic('R');
jrbYellow.setMnemonic('Y');
jrbGreen.setMnemonic('G');
jrbRed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(jrbRed.isSelected())
{
jrbRedClicked = true;
repaint();
}
}
});
jrbYellow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(jrbYellow.isSelected())
{
jrbYellowClicked = true;
repaint();
}
}
});
jrbGreen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(jrbGreen.isSelected())
{
jrbGreenClicked = true;
repaint();
}
}
}); // end of actionlistener()
} // end of trafficLights()
protected void paintComponent(Graphics g) {
super.paintComponents(g);
setBackground(Color.CYAN);
g.setColor(Color.BLACK);
g.drawRect(260, 50, 80, 160);
g.setColor(Color.BLACK);
g.drawRect(140, 50, 80, 160);
if(jrbRedClicked == true)
{
g.setColor(Color.RED);
g.fillOval(280, 60, 40, 40);
g.setColor(Color.BLACK);
g.drawOval(280, 110, 40, 40);
g.drawOval(280, 160, 40, 40);
g.drawRect(260, 50, 80, 160);
jrbRedClicked = false;
}
if(jrbYellowClicked == true)
{
g.setColor(Color.YELLOW);
g.fillOval(280, 110, 40, 40);
g.setColor(Color.BLACK);
g.drawOval(280, 50, 80, 160);
g.drawOval(280, 160, 40, 40);
g.drawRect(260, 50, 80, 160);
jrbYellowClicked = false;
}
if(jrbGreenClicked == true)
{
g.setColor(Color.GREEN);
g.fillOval(280, 160, 40, 40);
g.setColor(Color.BLACK);
g.drawOval(280, 60, 40, 40);
g.drawOval(280, 110, 40, 40);
g.drawRect(260, 50, 80, 160);
jrbGreenClicked = false;
}
}// end of paint component
} // end of public class