我是编程的新手(我11岁,希望java编码成为我的职业,但现在只是一个爱好:))我刚做了一个倒计时程序,这里是班级:
package me.NoahCagle.JAVA;
import javax.swing.JFrame;
public class Main extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
public static int width = 600;
public static int height = 500;
public static String title = "Countdown!";
public static boolean running = false;
public int number = 11;
public Thread thread;
Dimension size = new Dimension(width, height);
public Main() {
super(title);
setSize(size);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
Main m = new Main();
m.start();
}
public void start() {
if (running) {
return;
}
running = true;
Thread thread = new Thread(this);
thread.start();
}
@SuppressWarnings("static-access")
public void run() {
while (running) {
number--;
if (number == -1) {
System.out.println("Done!");
System.exit(0);
}
try {
thread.sleep(1000);
}catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
System.out.println("" + number);
}
}
public void stop() {
if (!running) {
return;
}
running = false;
try {
thread.join();
}catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
}
这可能没有必要,但无论如何。就像我说的那样,如果您阅读代码,您会注意到它将值打印到控制台。好吧,如果我可以在JLabel上显示,同时更新。我试过做setText(“”+ number),因为我有一个线程,它会重新绘制。但那并没有发生。它只是停留在11点。有人可以帮帮我吗?感谢
答案 0 :(得分:4)
首先,您可能需要阅读Concurrency in Swing。在处理多个线程和Swing时,有一些非常重要的限制。
对于您的问题,您确实应该使用javax.swing.Timer
,并使用示例...
答案 1 :(得分:-1)
11岁时,你在这里做得很好。但是你在哪里添加任何面板到你想要显示数字的框架?一旦你这样做并添加一些标签来添加数字,你需要调用重绘方法。另外,要使用带有摆动的线程,可以使用许多库,如Timer。
快乐的编码!