[英]Java drawn objects not updating properly
I have been playing around with Java's 2d painting tools and have hit a snag. 我一直在玩Java的2d绘画工具,遇到了麻烦。 I am attempting to move the objects.
我试图移动物体。 Here is the code:
这是代码:
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);
}
}
This only paints one of the two objects to the screen... it seems to be the second one as when I change the parameters of setLocation on [1] the one object it does paint moves. 这仅将两个对象之一绘制到屏幕上……似乎是第二个对象,因为当我在[1]上更改setLocation的参数时,它确实绘制了一个对象。 Any thoughts?
有什么想法吗? Thanks
谢谢
Edit: Edited above code to reflect what was said below. 编辑:编辑以上代码以反映下面所说的内容。
You are adding two components to the JFrame in a default way. 您将以默认方式将两个组件添加到JFrame。 This will add the components BorderLayout.CENTER and so the second component will cover and obscure the first.
这将添加组件BorderLayout.CENTER,因此第二个组件将覆盖第一个组件并使其模糊。 You will want to read up on layout managers to fix this.
您将需要阅读布局管理器以解决此问题。 Also read up on Swing Timers for simple animations, since your code, even if written correctly would do no animation.
另外,请阅读Swing计时器上的简单动画,因为即使正确编写代码,动画也不会起作用。
If you want to move the drawing, then 如果要移动图形,则
paintComponent(...)
method, not paint(...)
method. paintComponent(...)
方法,而不是paint(...)
方法。 super.paintComponent(g)
method first thing in your paintComponent method override. super.paintComponent(g)
方法。 repaint()
on the JPanel. repaint()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.