Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Adding an Event Listener to a "non-GUI"

807601Dec 11 2007 — edited Dec 13 2007
I'd be really grateful if someone could point me to the right place to find an answer...

I'm working on my first java mini application which cycles a set of traffic lights.
I want to stop the timed sequence with a key press to simulate the operator switching the system off, then carry out a graceful stop.

There is no applet or other (eg JFrame) GUI - just System.out.printlns to show the "lights" etc

I think I should be able to stop the sequence by listening for "x" for example - as a keyTyped (KeyEvent ke) but I cannot addKeyListener to my control object. All the examples in the books and in the documentation use GUIs.

I have overridden methods for keyPressed and keyReleased - it's just what to addKeyListener to that I am struggling with...

Here's my main method (which isn't right!)
public static void main (String[] args) {
    	SystemControl lightsAtElgin = new SystemControl();
    	//lightsAtElgin.addKeyListener(this); // this ain't right!
    	lightsAtElgin.systemStartUp(true);
    	lightsAtElgin.runSequence();
    	lightsAtElgin.systemStartUp(false); // never gets here...
    }
and here's the first (relevant bit of the class)...
public class SystemControl implements KeyListener { 

    private TrafficLightUnit unitOne = new TrafficLightUnit ("Unit One");
    private TrafficLightUnit unitTwo = new TrafficLightUnit ("Unit Two");
    private String systemSwitch; // operator switch
    private boolean notStopped;
    Scanner sc = new Scanner(System.in);
    
    // initialise with system switched off
    public SystemControl () {
    	systemSwitch = "OFF";
    	notStopped = false;
    }
    
    // key event interface methods...
    public void keyPressed(KeyEvent ke) {
    }
    
    public void keyReleased(KeyEvent ke) {
    }
    
    public void keyTyped(KeyEvent ke) {
    	char id = ke.getKeyChar();
    	String x = "x";
    	
    	if (x.equals(id)) {
    		notStopped = false;
    	} 
    	
    }
the timed sequence would break out like this...
while (notStopped) {
    // do sequence
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 10 2008
Added on Dec 11 2007
8 comments
493 views