作为一个初学者,我仍然需要一些关于如何同时使用线程和图形的解释。我想做的是非常基本的:只让两个球在一个框架内同时移动。这是我尝试过的:
public class Main extends JFrame
{
private static final long serialVersionUID = 1L;
private static final int _HEIGHT = 320, _WIDTH = 480;
private MyPanel panel;
public Main()
{
super("Test");
panel = new MyPanel();
this.setContentPane(panel);
this.setBounds(350,100,_HEIGHT,_WIDTH);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args)
{
new Main();
}
}
public class MyPanel extends JPanel
{
private static final long serialVersionUID = 1L;
ArrayList<Ball> listBalls;
public MyPanel()
{
this.setBackground(Color.WHITE);
listBalls = new ArrayList<Ball>();
listBalls.add(new Ball(30,30));
}
@Override
public void paint(Graphics gr)
{
Graphics2D g = (Graphics2D) gr;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(3f));
super.paint(g);
synchronized (listBalls) {
for(Ball b : listBalls)
{
b.drawItself(g);
}
}
}
}
public class Ball extends JPanel implements Runnable
{
private static final long serialVersionUID = 1L;
private int x, y;
private Thread thread;
public Ball(int x, int y)
{
this.x = x;
this.y = y;
}
public void drawItself(Graphics2D g)
{
g.setColor(Color.BLACK);
g.fillOval(x, y, 13, 13);
}
public void run()
{
Thread currentThread = Thread.currentThread();
while (thread == currentThread)
{
x+=2;
y+=2;
repaint();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
但这不起作用(球没有出现),我不知道该怎么做..请帮忙!