延迟后,提交JOptionPane并继续循环

时间:2016-02-28 08:23:40

标签: java multithreading timer joptionpane

所以我有这样的代码:

    for (int i = 0; i < totalNumPlayers; i++) {

                runTimer(30, myTextArea);

                players.get(i).bet = JOptionPane.showInputDialog(players.get(i).name + ", please enter your bet: ");

            }

我需要在计时器到期后自动提交JOptionPane(使用默认的int值)。

我的计时器代码:

    ScheduledExecutorService scheduledExecutorService =
            Executors.newScheduledThreadPool(1);

    ScheduledFuture scheduledFuture = scheduledExecutorService.schedule((Callable) () -> {

        for (int j = 1; j <= duration; j++) {

            myTextArea.replaceRange("\n" + String.valueOf(j), myTextArea.getText().lastIndexOf("\n"), myTextArea.getText().length());

            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Timer error!");
            }
        }
        return "Called!";

     }, 2, TimeUnit.SECONDS);

     scheduledExecutorService.shutdown();

1 个答案:

答案 0 :(得分:1)

实际上,这里有一个很好的方法closing-joptionpane-ShowInternalOptionDialog-programmatically

具体修改您的案例:

import javax.swing.JOptionPane;

public class Example {
    static String bet = "";
    public static void main(String[] args) {
        final JOptionPane pane = new JOptionPane();

        Thread t1 = new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                pane.getRootFrame().dispose();

            }
        });
        t1.start();
        bet = pane.showInputDialog("give me a value");

        if(bet == null)
            bet = "30";


        System.out.println(bet);
        System.exit(0);
    }
}

如果用户未提供任何输入,则JOptionPane会生成String bet = null。所以你检查一下,如果字符串是null,你只需为它分配自己的值。

另外,正如我在评论中所说,你可以用Timer来实现同样的目标。

import javax.swing.JOptionPane;
import javax.swing.Timer;
import java.awt.event.ActionListener;
import java.awt.event.*;

public class StackOverFlow {
    static String bet = "";
    public static void main(String[] args) {
        final JOptionPane pane = new JOptionPane();

        Timer t = new Timer(3000, new ActionListener() {
            public void actionPerformed(ActionEvent e ) {
                pane.getRootFrame().dispose();
            }
        });
        t.start();
        bet = pane.showInputDialog("give me a value");
        t.stop();

        if(bet == null) {
            bet = "30";
        }

        System.out.println(bet);
    }
}

两种方式都能实现同样的目标。值30显然可以由声明的常数给出。