作为初学者,我仍然需要一些关于如何同时使用线程和图形的解释。我想做的是非常基本的:只让两个球在一个框架内同时移动。这是我试过的:
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();
}
}
}
}
但这不起作用(球没有出现),我不知道该怎么做..请帮忙!
答案 0 :(得分:2)
Ball
无需延长JPanel
,您没有使用JPanel
或其子女的任何功能。paint
,建议您改用paintComponent
。很多原因,但你会喜欢的是paint
不是双缓冲的,paintComponent
是 - 闪烁的可能性更小Thread
,我建议您使用单个Thread
并更新其中的所有球,然后更新显示。这通常会减少您正在使用的资源数量,并使其更具可扩展性。Thread
,这意味着永远不会调用run
的{{1}}方法Swing中的并发性存在特殊问题。我建议您查看Concurrency in Swing以获取概述。
<强>更新强>
在SO上有很多优秀的例子,以下是我过去做过的一些......