简体   繁体   English

在Java中每隔X秒更改焦点按钮

[英]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, 我有5个按钮

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. 我想发生的是,按钮的焦点每5秒钟向下移动一个。 So the app starts and Button 1 has focus. 因此,该应用程序启动,并且按钮1具有焦点。 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. 然后5秒钟后,按钮2进行聚焦,依此类推,直到按钮5,然后返回按钮1。当我说聚焦时,我的意思是如果按下空格键,将按下该按钮。 Any assistance would be appreciated. 任何援助将不胜感激。 Thanks 谢谢

You could use a java swing timer for this task. 您可以使用Java Swing计时器执行此任务。 Take a look at the example in oracle docs 看一下oracle docs中的示例

http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html 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. 您可以创建一个可以休眠5秒的线程,然后唤醒并将焦点设置到下一个按钮。 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 您也可以使用java.util.Timer

You can use the KeyboardFocusManager for this as well. 您也可以为此使用KeyboardFocusManager。 Sample code below using Timer object from java.util. 下面的示例代码使用java.util中的Timer对象。 The code below changes focus every 500 ms. 下面的代码每500毫秒更改一次焦点。

    final KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();

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

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

    }, 0, 500);

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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