【发布时间】:2015-03-29 06:45:33
【问题描述】:
我是 Java swing 的新手。我想创建两辆从屏幕一端移动到另一端的汽车,现在我正在用一辆测试它。
但是经过三个动作(以“Inpaint component”打印3次表示)没有动作。
我已经附上了下面的完整代码。
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Polygon;
public class Application {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Demo");
Car car = new Car();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(car);
f.pack();
f.setVisible(true);
Thread thread = new Thread(car);
thread.start();
}
});
}
}
class Car extends JPanel implements Runnable {
private int xBase = 0, yBase = 50;
@Override
public Dimension getPreferredSize() {
return new Dimension(250, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("In paint component");
xBase = xBase + 20;
// Draw two wheels
g.setColor(Color.BLACK);
g.fillOval(xBase + 10, yBase - 10, 10, 10);
g.fillOval(xBase + 30, yBase - 10, 10, 10);
// Draw the car body
g.setColor(Color.BLUE);
g.fillRect(xBase, yBase - 20, 50, 10);
// Draw the top
g.setColor(Color.DARK_GRAY);
Polygon polygon = new Polygon();
polygon.addPoint(xBase + 10, yBase - 20);
polygon.addPoint(xBase + 20, yBase - 30);
polygon.addPoint(xBase + 30, yBase - 30);
polygon.addPoint(xBase + 40, yBase - 20);
g.fillPolygon(polygon);
}
@Override
public void run() {
try {
validate();
repaint();
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println(ex.getMessage());
}
}
}
我做错了什么。?
【问题讨论】:
标签: java multithreading swing repaint