0
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;

public class TrafficLight extends JFrame implements ActionListener {
    JButton b1, b2, b3;

      Signal green = new Signal(Color.green);
      Signal yellow = new Signal(Color.yellow);
      Signal red = new Signal(Color.red);

    public TrafficLight(){
        super("Traffic Light");
        getContentPane().setLayout(new GridLayout(2, 1));
        b1 = new JButton("Red");
        b2 = new JButton("Yellow");
        b3 = new JButton("Green");
        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);       

        green.turnOn(false);
        yellow.turnOn(false);
        red.turnOn(true);

        JPanel p1 = new JPanel(new GridLayout(3,1));
        p1.add(red);
        p1.add(yellow);
        p1.add(green);
        JPanel p2 = new JPanel(new FlowLayout());
        p2.add(b1);
        p2.add(b2);
        p2.add(b3);

        getContentPane().add(p1);
        getContentPane().add(p2);
        pack();
        }


    public static void main(String[] args){
        TrafficLight tl = new TrafficLight();       
        tl.setVisible(true);
    }   
    public void actionPerformed(ActionEvent e){       
        if (e.getSource() == b1){
            green.turnOn(false);           
            yellow.turnOn(false);
            red.turnOn(true);
        } else if (e.getSource() == b2){
            yellow.turnOn(true);           
            green.turnOn(false);
            red.turnOn(false);
        } else if (e.getSource() == b3){
            red.turnOn(false);           
            yellow.turnOn(false);
            green.turnOn(true);
        }
    }
}    
class Signal extends JPanel{

    Color on;
    int radius = 40;
    int border = 10;
    boolean change;

    Signal(Color color){
        on = color;
        change = true;
    }

    public void turnOn(boolean a){
        change = a;
        repaint();       
    }

    public Dimension getPreferredSize(){
        int size = (radius+border)*2;
        return new Dimension( size, size );
    }

    public void paintComponent(Graphics g){
        g.setColor( Color.black );
        g.fillRect(0,0,getWidth(),getHeight());

        if (change){
            g.setColor( on );
        } else {
            g.setColor( on.darker().darker().darker() );
        }
        g.fillOval( border,border,2*radius,2*radius );
    }
}

This creates a traffic light with 3 buttons that correspond to the colors and make them turn on one at a time. How can I make it alternate colors by just using the spacebar?

Currently the code has 3 different buttons that the user can interact with to determine the color that shines on the traffic light. I'm unsure of how to use the spacebar as a command to change the colors instead.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user2070292
  • 127
  • 1
  • 3
  • 8

3 Answers3

3

Have a look at using Key Bindings. A KeyStroke can be used for the SPACE key which can be mapped to an Action to cycle through a JButton array containing the red, yellow and green buttons and invoke doClick in order.

JPanel content = (JPanel) getContentPane(); // from JFrame
InputMap inputMap = content.getInputMap();
inputMap.put(KeyStroke.getKeyStroke("SPACE"), "pressed");
content.getActionMap().put("pressed", new AbstractAction() {
   public void actionPerformed(ActionEvent actionEvent) {
      currentButton = ++currentButton % buttons.length;
      buttons[currentButton].doClick();
   }
});

You can use the modulo operator % to keep the button index within range.

Unlike KeyListeners, Key Bindings do not require component focus to work so should always be preferred when developing Swing applications.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

Implement KeyListener interface and then use this code

public void keyPressed( KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode==KeyEvent.VK_SPACE){

   //Your Light Changing Code Here
...

}
droidchef
  • 2,237
  • 1
  • 18
  • 34
  • Swing was designed to be used with Key Bindings. See the Swing tutorial on [How to Use Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) for more information. – camickr Jun 03 '13 at 14:48
0

Sounds like you need a KeyListener. It behaves very similarly to an ActionListener, only it is specifically designed for your keyboard. Check out the API:

http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyListener.html

And the various keyEvents:

http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html

Russell Uhl
  • 4,181
  • 2
  • 18
  • 28
  • Swing was designed to be used with Key Bindings. See the Swing tutorial on [How to Use Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) for more information. – camickr Jun 03 '13 at 14:52