在 Java 中,我将 Timer 类事件侦听器附加到哪些对象? [英] Which objects do I attach the Timer class event listener to, in Java?

查看:35
本文介绍了在 Java 中,我将 Timer 类事件侦听器附加到哪些对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个打鼹鼠游戏.我已经使用 Swing 来创建背景并添加带有事件侦听器的痣图像,每次单击它们时都会增加一个分数,但是我在设置它们是否应该可见时遇到了问题.我认为最好的方法是使用计时器来设置/重置布尔值(vis).随机化图像可见的时间段将是理想的.我曾多次尝试使用摆动计时器,但似乎不起作用.在哪里实例化计时器,以及在计时器倒计时后执行代码的事件侦听器附加到什么位置?

I am trying to create a whack a mole game. I have used swing to create background and add mole images with event listeners which increment a score each time they are clicked, but I am having problems setting whether they should be visible or not. I thought the best way to do this would be to use a timer to set/reset a boolean (vis). Randomizing the period for which the images are visible would be ideal. I have tried using a swing timer several times but doesn't seem to be working. Where do I instantiate the timer, and to what do I attach the event listener which executes the code after the timer has counted down?

package whackmole;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

public class WhackAMole extends JFrame {

public WhackAMole() {
    createAndShowGUI();
}

static int score = 0;
public static JLabel scoreDisplay;
boolean vis;

public static void main(String[] args) throws Exception {
    // run asynchronously
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

private static void createAndShowGUI() {

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setMinimumSize(new Dimension(600, 600));
    Holes holes = new Holes(frame);
    frame.getContentPane().add(holes);
    holes.setLayout(null);
    frame.pack();
    frame.setVisible(true);

    scoreDisplay = new JLabel("Score: " + score);
    scoreDisplay.setBounds(239, 11, 84, 38);
    holes.add(scoreDisplay);

    Mole mole = new Mole(68, 92, true);
    mole.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            score++;
            scoreDisplay.setText("Score: " + score);
        }
    });
    holes.add(mole);

    Mole mole2 = new Mole(181, 320, false);
    mole2.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            score++;
            scoreDisplay.setText("Score: " + score);
        }
    });
    holes.add(mole2);

    Mole mole3 = new Mole(414, 439, true);
    mole3.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            score++;
            scoreDisplay.setText("Score: " + score);
        }
    });
    holes.add(mole3);

    Mole mole4 = new Mole(297, 203, false);
    mole4.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            score++;
            scoreDisplay.setText("Score: " + score);
        }
    });
    holes.add(mole4);
 }
}

推荐答案

在这种情况下,您可以实例化您的 Timer 具有固定速率和一个实现 ActionListener 的类.

In this context, you can instantiate your Timer with a fixed rate and a class that implements ActionListener.

public class Example extends JPanel implements ActionListener {
    private static final int RATE = 1000 / 8; // ~8 Hz
    private final Timer timer = new Timer(RATE, this);
}

在这个完整的示例中,GameButton是一个子类JToggleButtonActionListener 的实现只是切换随机选择的 GameButton 的状态.

In this complete example, GameButton is a subclass of JToggleButton, and the implementation of ActionListener simply toggles the state of a randomly selected GameButton.

private final List<GameButton> buttons = new ArrayList<GameButton>(MAX);
public void actionPerformed(ActionEvent e) {
    Object src = e.getSource();
    if (src == timer) {
        int index = random.nextInt(game.max());
        GameButton gb = buttons.get(index);
        gb.setSelected(!gb.isSelected());
    }
    ...
}

为了区分状态,示例使用了 Unicode 字形,但您可以使用 setIcon()setSelectedIcon().

To distinguish states, the example uses Unicode glyphs, but you can use setIcon() and setSelectedIcon().

这篇关于在 Java 中,我将 Timer 类事件侦听器附加到哪些对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆