我正在制作摇摆迷宫游戏,我在游戏中使用cardlayout从面板转到面板(主菜单 - >选择难度屏幕 - >游戏屏幕) 。
我已经设置了我的游戏和菜单,现在我正在尝试添加一个倒计时时钟,让用户知道他在比赛结束前还有X秒数。
我做了一个倒数计时器,它适用于1个地图(1个面板),但是当我尝试将它用于其他面板(我的其他2个地图)时。它真的很麻烦。计时器在达到0(选项窗格和哔声)后不会停止执行操作。
所以TimerEvent和TimerClass类在我将它们链接到我的GUI时会起作用(我在这里发布的其他gui,但是在这里发布许多行的方式)。但是当我尝试向其他面板添加更多计时器时(我的游戏之间的不同级别),它会变得非常多。
抱歉我的英文不好,非常感谢你!
真诚地,初学者程序员
package labyrinthproject.View;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Card {
public static void main(String[] args) {
JFrame frame = new JFrame();
final JPanel panelCont = new JPanel();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JLabel timerLabel = new JLabel();
JButton gopanel1 = new JButton("go panel1");
JButton gopanel2 = new JButton("go panel2");
final CardLayout cl = new CardLayout();
panelCont.setLayout(cl);
frame.setPreferredSize(new Dimension(800,600));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panelCont);
frame.pack();
panel1.setPreferredSize(new Dimension(800,600));
panel1.setBackground(Color.red);
panel1.add(gopanel1);
panel1.add(gopanel2);
gopanel1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cl.show(panelCont, "2");
}
});
gopanel2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cl.show(panelCont, "3");
}
});
panel2.setPreferredSize(new Dimension(800,600));
panel2.setBackground(Color.black);
panel2.add(timerLabel)
panel3.setPreferredSize(new Dimension(800,600));
panel3.setBackground(Color.blue);
panelCont.add(panel1, "1");
panelCont.add(panel2, "2");
panelCont.add(panel3, "3");
frame.setVisible(true);
}
}
public class TimerEvent implements ActionListener {
static TimerEvent e = new TimerEvent();
public void actionPerformed(ActionEvent e){
int count = 60;
Card.timerLabel.setText("Time: " + count);
TimerClass tc = new TimerClass(count);
Card.timer = new Timer(1000, tc);
Card.timer.start();
}
}
public class TimerClass implements ActionListener {
int counter;
public TimerClass(int counter) {
this.counter = counter;
}
public void actionPerformed(ActionEvent tc) {
counter--;
if (counter >= 1) {
Card.timerLabel.setText("Time:" + counter);
} else {
Card.timer.stop();
Card.timerLabel.setText("Done");
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(MainMenu.panelCont, "Time expired, game over");
Card.cl.show(MainMenu.panelCont, "2");
Card.timer.stop();
}
}
}
答案 0 :(得分:0)
为什么不这样做:
int counter;
for (int j = 0 ; j >=counter ; j++) {
Card.timerLabel.setText("Time:" + counter);
delayer (1000);
}
private static void delayer (long milliseconds)
{
try {
Thread.sleep (1000);
}
catch (InterruptedException ex){
}
}