我在做简单的计数器。我的问题是drawString()方法在旧字符串上绘制新字符串。如何清除之前的旧版本?代码...
package foobar;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class board extends JPanel implements Runnable {
Thread animator;
int count;
public board() {
this.setBackground( Color.WHITE );
count = 0;
animator = new Thread( this );
animator.start();
}
@Override
public void run() {
while( true ) {
++count;
repaint();
try {
animator.sleep( 1000 );
} catch ( InterruptedException e ) {}
}
}
@Override
public void paint( Graphics Graphics ) {
Graphics.drawString( Integer.toString( count ), 10, 10 );
}
}附注:我是Java新手,所以请不要害怕告诉我我应该在我的代码中修复什么其他东西……
发布于 2011-04-30 22:30:27
代码中有几个问题:
编辑:
我的错,你的while (true)和Thread.sleep(...) 将工作,因为它们在后台线程中,但是,...
<>F219
例如,
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Board2 extends JPanel {
private static final int TIMER_DELAY = 1000;
private int counter = 0;
private JLabel timerLabel = new JLabel("000");
public Board2() {
add(timerLabel);
new Timer(TIMER_DELAY, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
counter++;
timerLabel.setText(String.format("%03d", counter));
}
}).start();
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Board2");
frame.getContentPane().add(new Board2());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}发布于 2011-04-30 22:30:02
我想Graphics.clearRect就是你要找的人。
发布于 2011-04-30 22:33:04
我会这样做:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
//draw all the other stuff
}https://stackoverflow.com/questions/5842360
复制相似问题