I would need to get the location coordinates of all the drawings I'm creating in the paintComponent method. How can I do this?
Notice that I use the timer to perform some animations so the coordinates change at every tick of the timer.
public class TestPane extends JPanel {
private int x = 0;
private int y = 100;
private int radius = 20;
private int xDelta = 2;
public TestPane() {
Timer timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
x += xDelta;
if (x + (radius * 2) > getWidth()) {
x = getWidth() - (radius * 2);
xDelta *= -1;
} else if (x < 0) {
x = 0;
xDelta *= -1;
}
label.setText(x+" "+y);
repaint();
}
});
timer.start();
}
More code...
protected void paintComponent(Graphics g) {
Random random = new Random();
super.paintComponent(g);
g.setColor(Color.ORANGE);
g.fillOval(random.nextInt(500), random.nextInt(500) - radius, radius * 2, radius * 2);
g.setColor(Color.BLUE);
g.fillOval(y, x - radius, radius * 2, radius * 2);
// label.setText(label.getText()+ x+" "+y); ;
g.setColor(Color.RED);
g.fillOval(x, y - radius, radius * 2, radius * 2);
// label.setText(label.getText()+ x+" "+y);
}
Your program should maintain a List<Node>
as a class level attribute. Each instance of Node
should contain the geometry required to render each element in your program.
class Node {
private Point p;
private int r;
…
}
In your ActionListener
, update the fields of each Node
in the List
. When a repaint()
occurs, the new positions will be waiting for paintComponent()
to render.
@Override
public void paintComponent(Graphics g) {
…
for (Node n : nodes) {
// draw each node
}
A complete example, named GraphPanel
, is cited here.