我正在研究简单的计数器。我的问题是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 );
}
}
P.S。我是Java的新手,所以请不要害怕告诉我我的代码中应该修复的其他内容......
答案 0 :(得分:7)
代码中的几个问题:
编辑:
如,
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();
}
});
}
}
答案 1 :(得分:1)
我认为Graphics.clearRect正是您所寻找的。 p>
答案 2 :(得分:1)
我会这样做:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
//draw all the other stuff
}
答案 3 :(得分:1)
啊哈!这个是正常的。想象一下,您的面板是黑板。每当你想要重新绘制你所写的内容时,你必须首先删除黑板。
在Java中,以及在图形中,事情都是以类似的方式进行的。在您的绘画方法中,执行以下操作:
Graphics.clearRect(0,0, getWidth(),getHeight());
//CLEAR the entire component first.
Graphics.drawString(...); //now that the panel is blank, draw the string.
如果您可以更好地处理该主题,请执行super.paint(Graphics)
而不是clearRect()
。