我对Java Swing不太满意,并且尝试使用计时器以3秒的延迟启动游戏
但同时我想显示一个对话框(游戏也必须等待3秒,因此焦点必须放在对话框上)
所以我的对话框如下:got this sample code
因此,在我的游戏面板中,我这样做:
public class GamePlayPanel extends JPanel implements ActionListener {
// attributes
private JOptionCountDownTimer countDownDialog;
public GamePlayPanel(MainWindow mainWindow) {
// initialization attributes
initLayoutPanel();
this.timer = new Timer(DELAY, this);
// Added a delay of 3 seconds so you can prepare to for the game
this.timer.setInitialDelay(3000);
resetTime();
}
public void startGame() {
this.gamePanel.requestFocus();
this.countDownDialog.startCountDown();
startTimer(); // this is my game timer to record the game time
}
public void restartGame() {
this.countDownDialog.resetCountDown();
startTimer();
this.gamePanel.requestFocus();
}
}
它工作正常,但如果我重新启动游戏,则倒数计时器将从0-> 2秒开始。
在我的课程
JOptionCountDownTimer
上还有更好的主意吗?我试图使其扩展JDialog
类,但无法使其正常工作。 最佳答案
试试看,看看是否适合您。您可以仅获取对话框类代码。您需要做的就是将父框架传递给它,对于模态和所需的秒数则为true。您可能还想修饰它。我只是提供功能
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
public class CountDownTimer {
public CountDownTimer() {
final JFrame frame = new JFrame();
JButton button = new JButton("Open Dilaog");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
new CountDownTimerDialog(frame, true, 5);
}
});
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private class CountDownTimerDialog extends JDialog {
private int count;
public CountDownTimerDialog(JFrame parent, boolean modal, int seconds) {
super(parent, modal);
count = seconds;
final JLabel countLabel = new JLabel(String.valueOf(seconds), JLabel.CENTER);
countLabel.setFont(new Font("impact", Font.PLAIN, 36));
JLabel message = new JLabel("Wait to Start Game");
message.setFont(new Font("verdana", Font.BOLD, 20));
JPanel wrapper = new JPanel(new BorderLayout());
wrapper.setBorder(new EmptyBorder(10, 10, 10, 10));
wrapper.add(countLabel);
wrapper.add(message, BorderLayout.SOUTH);
add(wrapper);
Timer timer = new Timer(1000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (count == -1) {
dispose();
} else {
countLabel.setText(String.valueOf(count));
count--;
}
}
});
timer.setInitialDelay(0);
timer.start();
pack();
setLocationRelativeTo(parent);
setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new CountDownTimer();
}
});
}
}