获取paintComponent中多个绘图的位置

Get location of multiple drawings in paintComponent

我需要获取我在 paintComponent 方法中创建的所有绘图的位置坐标。我该怎么做?

请注意,我使用计时器来执行一些动画,因此坐标会在计时器的每个滴答声中发生变化。

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();
    }

更多代码...

 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);
        }

您的程序应维护 List<Node> 作为 class 级别属性。 Node 的每个实例都应包含呈现程序中每个元素所需的几何图形。

class Node {
    private Point p;
    private int r;
    …
}

在您的 ActionListener 中,更新 List 中每个 Node 的字段。当 repaint() 发生时,新位置将等待 paintComponent() 呈现。

@Override
public void paintComponent(Graphics g) {
    …
    for (Node n : nodes) {
        // draw each node
    }

引用了一个名为 GraphPanel 的完整示例 here