将计时器添加到Java Swing

编程入门 行业动态 更新时间:2024-10-26 19:31:11
本文介绍了将计时器添加到Java Swing的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

好吧,我很抱歉在短时间内发布了多个问题,但我正试图让这个时间从3倒数到0 ......这是我的代码

Well I'm Sorry For Posting More Than One Question In A Short Amount Of Time But I Am Trying To Have This Time Count Down From 3 To 0... Here's My Code

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ClickingGame extends JPanel implements ActionListener { private static final long serialVersionUID = 1L; static JFrame frame; static JButton startbutton, clickingbutton, timerstop; static JLabel timelabel, scorelabel; static int time = 3; static JTextField entertime; static Timer clock; static Timer countdown; static int score = 0; public ClickingGame() { setLayout(new GridLayout(3, 2, 5, 5)); startbutton = new JButton("Start CountDown"); timelabel = new JLabel("Time Left = NULL", SwingConstants.CENTER); entertime = new JTextField(); clickingbutton = new JButton("Click Here!"); scorelabel = new JLabel("Score = NULL", SwingConstants.CENTER); timerstop = new JButton("Stop Timer!"); clock = new Timer(1000, this); countdown = new Timer(1000, this); add(entertime); add(startbutton); add(timelabel); add(scorelabel); add(clickingbutton); add(timerstop); clickingbutton.setEnabled(false); timerstop.setEnabled(false); startbutton.addActionListener(this); clickingbutton.addActionListener(this); } public static void openGUI() { frame = new JFrame("Clicking Game"); ClickingGame contentpane = new ClickingGame(); frame.setContentPane(contentpane); frame.pack(); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource() == startbutton) { startbutton.setEnabled(false); clickingbutton.setEnabled(true); time--; if (time > 0) { countdown.start(); timelabel.setText("Starting In: " + time); } else { countdown.stop(); time = 3; } } if (e.getSource() == clickingbutton) { score++; scorelabel.setText("Score = " + score); } } }

你可以看到我有我的计时器倒计时设置正确,它只计算一次...我试图让它倒数一路到3 ...

As You Can See I Have My Timer "countdown" Set Up Right, It Only Counts Down Once... I Am Trying To Get It To Count Down All The Way To 3...

推荐答案

您需要在 actionPerformed 中为倒计时对象添加一个案例作为来源。

You need to add a case in your actionPerformed for your countdown object as the source.

编辑:

您可以尝试这样的事情:

you could try something like this:

if (e.getSource() == startbutton) { startbutton.setEnabled(false); clickingbutton.setEnabled(true); if (time > 0) { countdown.start(); timelabel.setText("Starting In: " + time); } } if (e.getSource() == countdown){ timelabel.setText("Starting In: " + time); if (time == 0) { countdown.stop(); time = 3; } else { time--; } }

更多推荐

将计时器添加到Java Swing

本文发布于:2023-10-31 07:55:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545501.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:计时器   Java   Swing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!