实际上,这里有一个很好的方法closing-joptionpane-ShowInternalOptionDialog-programmatically
所以我有这样的代码:
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();
所以我有这样的代码:for(int i = 0; i
具体针对您的情况进行修改:
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
。因此,您进行了检查,如果String为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显然可以由声明的常数给出。