As a beginner at this, I still need some explanations of how to use Threads and Graphics at the same time. What I want to do is very basic : only make two balls move simultaneously in a frame. Here is what I tried :
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();
}
}
}
}
But this won't work (the balls don't appear), and I've no idea of what to do.. please help!