根据众多 Stackoverflow 用户的建议,这里正确的方法是使用 javax.swing.TImer。以下是一个小代码片段以供参考。如果有超出您理解范围的问题,请随时询问,我会提供相应的信息。
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class DrawStringWithTimer
{
private final int WIDTH = 400;
private final int HEIGHT = 300;
private Timer timer;
private int x;
private int y;
private int counter;
private Random random;
private String[] messages = {
"Bingo, I am ON",
"Can you believe this !!",
"What else you thinking about ?",
"Ahha, seems like you are confused now !!",
"Lets Roll and Conquer :-)"
};
private CustomPanel contentPane;
private ActionListener timerAction = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
if (counter == 5)
counter = 0;
x = random.nextInt(WIDTH);
y = random.nextInt(HEIGHT);
contentPane.setValues(x, y, messages[counter]);
counter++;
}
};
public DrawStringWithTimer()
{
counter = 0;
x = y = 10;
random = new Random();
}
private void displayGUI()
{
JFrame frame = new JFrame("Drawing String Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new CustomPanel(WIDTH, HEIGHT);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
timer = new Timer(2000, timerAction);
timer.start();
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new DrawStringWithTimer().displayGUI();
}
});
}
}
class CustomPanel extends JPanel
{
private final int GAP = 10;
private int width;
private int height;
private int x;
private int y;
private String message = "";
public CustomPanel(int w, int h)
{
width = w;
height = h;
setOpaque(true);
setBackground(Color.WHITE);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
}
public void setValues(int x, int y, String msg)
{
this.x = x;
this.y = y;
message = msg;
repaint();
}
@Override
public Dimension getPreferredSize()
{
return (new Dimension(width, height));
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString(message, x, y);
}
}
Swing JComponents
和AWT / Swing
中进行绘画,正如@trashgod所指出的那样,只使用Swing Timer
。 - mKorbel