Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 获取paintComponent中多个图形的位置_Java_Swing_Graphics_Paintcomponent - Fatal编程技术网

Java 获取paintComponent中多个图形的位置

Java 获取paintComponent中多个图形的位置,java,swing,graphics,paintcomponent,Java,Swing,Graphics,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() {

我需要获得在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();
    }

您的程序应该维护一个
列表
,作为类级属性。
节点的每个实例
都应该包含渲染程序中每个元素所需的几何体

class Node {
    private Point p;
    private int r;
    …
}
ActionListener
中,更新
列表中每个
节点的字段。当发生
repaint()
时,新位置将等待
paintComponent()
渲染

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

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

“我需要获得我正在创建的所有图形的位置坐标…”嗯。。对于其中两个,您提供x的任意y,对于另一个,您可以在使用前将
random.nextInt(500)
存储在类级属性中。。如果这不是一个解决办法,我不明白这个问题@对不起,我在顶部加了计时器。因此,每当计时器滴答声时,位置都会改变。请参阅所引用示例中的
列表
。@trashgood我看不到任何
列表
“因此,每当计时器滴答声时,位置都会改变。”我..看不出这会如何改变我前面所说的任何内容。(耸耸肩)投票结束,因为“不清楚你在问什么”。
@Override
public void paintComponent(Graphics g) {
    …
    for (Node n : nodes) {
        // draw each node
    }