我一直在使用 Java 的 2d 绘画工具,但遇到了障碍。我正在尝试移动物体。这是代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test extends JPanel{
private int[] location = new int[2];
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillArc(location[0], location[1], 100, 100, 45, 90);
g.setColor(Color.black);
g.fillArc((location[0]+50-10),(location[1]+50-10), 20, 20, 0, 360);
new Timer(2000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setLocation((location[0]+50),50);
repaint();
System.out.println("repainting");
}
}).start();
}
public void setLocation(int x, int y){
this.location[0] = x;
this.location[1] = y;
}
public static void main(String[] args){
JFrame jf=new JFrame();
jf.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
jf.setPreferredSize(new Dimension(300,500));
jf.setLocation(100,100);
jf.add(new Test());
jf.pack();
jf.setVisible(true);
}
}
这只会将两个对象之一绘制到屏幕上...它似乎是第二个,因为当我更改 [1] 上的 setLocation 参数时,它绘制的一个对象会移动。有什么想法吗?谢谢
编辑:编辑上面的代码以反射(reflect)下面所说的内容。
最佳答案
您正在以默认方式向 JFrame 添加两个组件。这将添加组件 BorderLayout.CENTER,因此第二个组件将覆盖并遮盖第一个组件。您需要阅读布局管理器来解决这个问题。另请阅读 Swing Timers 以了解简单的动画,因为即使编写正确,您的代码也不会执行任何动画。
如果你想移动绘图,那么
- 仅使用一个测试 JPanel
- 重写 JPanel 的
paintComponent(...)
方法,而不是paint(...)
方法。 - 在 PaintComponent 方法重写中首先调用
super.paintComponent(g)
方法。 - 为 Test JPanel 提供公共(public)方法,以允许外部类更改位置,而无需直接处理该字段。为了安全起见,将位置字段(名称应以小写字母开头)设置为私有(private)。
- 使用 Swing Timer 定期调用此方法并更改位置,然后在 JPanel 上调用
repaint()
。
关于Java 绘制的对象未正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16804681/