好像我的图形对象是最终的,因为错误表明我永远无法更改它。在我的计时器循环中使用它们之前,我一直在阅读有关将变量分配给最终变量的信息,以解决这个问题,但我什至不知道如何开始为图形对象处理它。我需要将最终的图形对象复制回普通的图形对象吗?这是一些代码。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.util.ArrayList;
public class Test extends JPanel{
abstract class graphic {
public Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
public int[] location = new int[] {screenSize.width/2,screenSize.height/2};
}
public class gladiator extends graphic {
void draw(Graphics g) {
g.setColor(Color.green);
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);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
gladiator[] gladiator = new gladiator[2];
ArrayList<gladiator> gladiatorList = new ArrayList<gladiator>();
for (int a =0; a < 2; a++) {
final gladiator[a] = new gladiator();
final gladiatorList.add(gladiator[a]);
}
new Timer(200, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int a = 0; a < gladiatorList.size(); a++) {
gladiator[a].draw(g);
}
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(Toolkit.getDefaultToolkit().getScreenSize());
jf.add(new Test());
jf.pack();
jf.setVisible(true);
}
}
这是返回 for 循环内几乎所有行都应该是最终行的位。
new Timer(200, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int a = 0; a < gladiatorList.size(); a++) {
gladiator[a].draw(g);
}
repaint();
System.out.println("repainting");
}
}).start();
谢谢!