Java计时器问题

时间:2011-11-27 05:19:46

标签: java swing timer actionlistener

我有一个模拟咖啡自动售货机的小程序。我试图让文本准备好显示5秒钟。但它似乎没有奏效。谁能告诉我我的计时器有什么问题?

类qn1是JApplet的类。 将调用init()来实例化变量。

我将actionlistener添加到2个按钮,这样当我点击它们时它们会做出反应。

    import java.awt.*;
    import java.awt.event.*;

    import javax.swing.*;
    import javax.swing.event.*;

    public class qn1 extends JApplet implements ActionListener {

        private static int FULL = 4;
        private int coffees = FULL;
        private JPanel p;
        private JButton jbtw, jbtb;
        private Dispenser dis;
        private JLabel jlbl;
        private Timer timer;

        public void init() {
            setLayout(new BorderLayout(5, 5));
            setSize(400, 500);

            p = new JPanel(new GridLayout(1, 2));
            jbtw = new JButton("White");
            jbtb = new JButton("Black");
            jbtw.addActionListener(this);
            jbtb.addActionListener(this);
            p.add(jbtw);
            p.add(jbtb);

            add(p, BorderLayout.NORTH);

            dis = new Dispenser();
            add(dis, BorderLayout.CENTER);

            jlbl = new JLabel("Select", SwingConstants.CENTER);
            add(jlbl, BorderLayout.SOUTH);

            timer = new Timer(50, this);
        }

        public void actionPerformed(ActionEvent e) {
            if (e.getSource().equals(jbtb) | e.getSource().equals(jbtw)) {
                if (coffees - 1 >= 0) {
                    coffees--;
                    jlbl.setText("Ready " + coffees);               
                }

                timer.setInitialDelay(5000);
                timer.start();  

                if (coffees == 0) {
                    jlbl.setText("Empty");
                } else {
                    jlbl.setText("Select" + coffees);
                }
            }
        }
    }

    class Dispenser extends JPanel {
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawLine(0, 0, 25, 50);
            g.drawLine(25, 50, 55, 50);
            g.drawLine(55, 50, 80, 0);
        }
    }

1 个答案:

答案 0 :(得分:3)

您的计时器已被调用,但如果源不是您的某个按钮,则您不执行任何操作:

    if (e.getSource().equals(jbtb) | e.getSource().equals(jbtw)) {

要回答您的意见,您可能需要这样的内容:

    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(jbtb) | e.getSource().equals(jbtw)) {
            timer.setInitialDelay(5000);
            timer.start();  

            if (coffees == 0) {
                jlbl.setText("Empty");
            } else {
                jlbl.setText("Select " + coffees);
            }
        }
        else {
            if (coffees - 1 >= 0) {
                coffees--;
                jlbl.setText("Ready " + coffees);               
            }
        }
    }