简体   繁体   中英

Change focused button every x seconds in java

I'm looking for the best way to do the following. If someone could point me in the right direction I'd be greatfull.

I have 5 buttons,

Button 1
Button 2
Button 3
Button 4
Button 5

What I'd like to happen is every 5 seconds the focus of the button move one down. So the app starts and Button 1 has focus. Then 5 seconds later button 2 takes focus and so on so on until Button 5 and then back to Button 1. When I say focus I mean that if the space bar was pressed the button would be pressed. Any assistance would be appreciated. Thanks

You could use a java swing timer for this task. Take a look at the example in oracle docs

http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html

You can create thread that sleeps for 5 senconds, then awakes and sets focus to the next button. Store your buttons in array.

final int n = 5;
final int TIMEOUT = 5000;
Button[] buttons = new Button[n];
// fill the array

new Thread() {
    for (i = 0;  ;  i < n ? i++ : i = 0) {
        buttons.requestFocusInWindow();
        try {
            Thread.sleep(TIMEOUT);
        } catch(InterruptedException e) {}
    }
}.start();

You can also use java.util.Timer

You can use the KeyboardFocusManager for this as well. Sample code below using Timer object from java.util. The code below changes focus every 500 ms.

    final KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            manager.focusNextComponent();
        }

    }, 0, 500);

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM