定时器时闪烁,当它到达0
问题描述:
导入库定时器时闪烁,当它到达0
public class Countdown1 extends Applet implements Runnable {
// getting user input
String input = JOptionPane.showInputDialog("Enter seconds: ");
// converting string to integer
int counter = Integer.parseInt(input);
Thread countdown;
public void start() {
countdown = new Thread(this);
countdown.start();
}
// executed by thread
public void run() {
Timer timer;
timer = new Timer(1000, new ActionListener() /* counting down time inputted */ {
public void actionPerformed(ActionEvent evt) {
if (counter > 0) {
counter--;
// repainting each second
repaint();
}
}
});
// timer started
timer.start();
}
public void paint(Graphics g) {
//painting text and time
g.setFont(new Font("Times New Roman", Font.BOLD, 35));
g.drawString("Seconds: " + String.valueOf(counter), 260, 210);
setBackground(Color.orange);
setForeground(Color.magenta);
// change background to cyan when timer reaches 0
if (counter == 0) {
setBackground(Color.cyan);
}
}
}
答
的问题是不是你的Timer
(虽然我做题,需要一个单独的线程中启动它),问题是绝对基于paint
。
像Applet
这样的顶级容器没有双缓冲,这意味着每个绘画动作都倾向于被迫发送到底层的Graphics
设备。
现在,您可以通过以上雇员或走到这一些双缓冲过程你能...
- 从
JApplet
扩展,而不是 - 创建一个从东西延伸的自定义组件,像
JPanel
并重写它的paintComponent
方法来代替,将您的自定义绘画移动到此方法 - 改为将此组件添加到小程序。
应该解决眼前的问题......
你也应该避免调用setForeground
或setBackground
任何paint
方法中。事实上,你应该避免调用可能调用repaint
任何paint
方法中的任何方法...
我敢肯定,这String input = JOptionPane.showInputDialog("Enter seconds: ");
是一个坏主意。相反,你应该提供某种控制或选项的用户界面中更改该值...
原油例如
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Countdown1 extends JApplet {
@Override
public void init() {
add(new CounterPane());
}
public class CounterPane extends JPanel {
String input = JOptionPane.showInputDialog("Enter seconds: ");
int counter = Integer.parseInt(input);
public CounterPane() {
Timer timer;
timer = new Timer(1000, new ActionListener() /* counting down time inputted */ {
public void actionPerformed(ActionEvent evt) {
System.out.println(counter);
if (counter > 0) {
counter--;
setBackground(Color.orange);
setForeground(Color.magenta);
if (counter <= 0) {
setBackground(Color.cyan);
}
repaint();
}
}
});
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(new Font("Times New Roman", Font.BOLD, 35));
g.setColor(getForeground());
g.drawString("Seconds: " + String.valueOf(counter), 260, 210);
}
}
}
感谢,感激大大 –
希望它可以帮助你用自己的方式;) – MadProgrammer
这是相当滞后的,但是当我从JApplet扩展而不是Applet时,我的背景颜色变回白色,计时器正在重绘上一个数字的顶部。 –