JAVA:如何缩短计时器运行时的计时器时间?

时间:2016-04-08 18:10:06

标签: java swing timer

问题

我想每次输入错误的答案减少时间,我有更多这样的面板,我想当我移动到下一个面板的时间开始,而不是当我编译文件时计时器启动同一时间

输出

enter image description here

代码

    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 

1 个答案:

答案 0 :(得分:1)

  1. 您应该使用Swing Timer而不是AWT计时器。阅读API有一些方法可以让你设置/更改定时器延迟。

  2. 不要使用KeyListener来处理文本字段上的Enter键。相反,您应该在文本字段中添加ActionListener。然后,Enter键将调用该操作。