问题
我想让每次输入错误答案时减少时间,并且我有更多这样的面板,我想让当我移动到下一个面板时开始时间,而不是当我编译文件时计时器同时开始.
输出
代码
int time = 7000;
ans2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(ans2.getText().toUpperCase().equals("CAT")){
word.setText("CAT");
ans2.setText("");
if(word.getText().equals("CAT") && word2.getText().equals("CARD") && word3.getText().equals("TILES") && word4.getText().equals("MIRROR") && word5.getText().equals("COUCH") && word6.getText().equals("STRAW")){
JOptionPane.showMessageDialog(null, "COMPLETE\n Go to Next Stage");
word.setText(""); word2.setText(""); word3.setText(""); word4.setText(""); word5.setText(""); word6.setText("");
timer.stop();
CardLayout cl = (CardLayout) main.getLayout();
cl.show(main, "Stage2");
}
}
//i want to make "else if wrong answer time reduce 2 sec"
}
});
JProgressBar progressBar = new JProgressBar(JProgressBar.HORIZONTAL, 0, 70);
progressBar.setValue(70);
progressBar.setPreferredSize(new Dimension(600, 20));
ActionListener listener = new ActionListener() {
int counter = 70;
public void actionPerformed(ActionEvent ae) {
counter--;
progressBar.setValue(counter);
if (counter<1) {
JOptionPane.showMessageDialog(null, "Game Over!");
timer.stop();
CardLayout cl = (CardLayout) main.getLayout();
cl.show(main, "Main Menu");
}
}
};
timer = new Timer(time, listener);
timer.start();// i have main menu and i want the timer start when i press start button in main menu
最佳答案
您应该使用
Swing Timer
而不是 AWT 计时器。阅读 API,其中有允许您设置/更改计时器延迟的方法。不要使用 KeyListener 来处理文本字段上的 Enter 键。相反,您应该将 ActionListener 添加到文本字段。然后按 Enter 键将调用该操作。
关于JAVA : How do I reduce the timer's time when the timer is running?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36506477/