当我运行以下代码时,我得到两个相同的错误:无法从静态上下文引用非静态方法。两条违规行是:
gladiator[a] = new Gladiator();
graphic.startUpdate();
如果我将 Gladiator 类更改为 static,该错误就会消失,但这不会导致个别 Gladiator 不能拥有自己的自变量吗?
startUpdate() 方法不允许我将其更改为静态而不引发错误,即“仅在常量变量声明中允许使用修饰符静态”。显然我在错误的地方使用了我的更新计时器。有任何想法吗?
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};
void startUpdate() {
new Timer(200, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}).start();
}
}
public class Gladiator extends graphic {
void draw(final 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(final Graphics g) {
super.paintComponent(g);
}
public void setLocation(int x, int y){
//this.location[0] = x;
//this.location[1] = y;
}
public static void main(String[] args){
Gladiator[] gladiator = new Gladiator[2];
ArrayList<Gladiator> gladiatorList = new ArrayList<Gladiator>();
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 (int a =0; a < 2; a++) {
gladiator[a] = new Gladiator();
gladiatorList.add(gladiator[a]);
System.out.println("add "+a);
}
graphic.startUpdate();
}
}