我知道有很多关于动作监听器等的问题。但是,没有一个可以帮助我解决我的具体问题......无论我尝试哪种方式,我总是会遇到错误。这是我的简单弹跳球程序:
public class ControlledBall extends JPanel implements Runnable {
int diameter;
long delay;
private int x;
private int y;
private int vx;
private int vy;
public ControlledBall(int xvelocity, int yvelocity) {
diameter = 30;
delay = 40;
x = 1;
y = 1;
vx = xvelocity;
vy = yvelocity;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g.setColor(Color.blue);
g.fillOval(x,y,30,30);
g.setColor(Color.black);
g2.drawOval(x,y,30,30); //draw
}
public void run() {
while(isVisible()) {
try {
Thread.sleep(delay);
} catch(InterruptedException e) {
System.out.println("Something Went Wrong!");
}
move();
repaint();
}
}
public void move() {
if(x + vx < 0 || x + diameter + vx > getWidth()) {
vx *= -1;
}
if(y + vy < 0 || y + diameter + vy > getHeight()) {
vy *= -1;
}
x += vx;
y += vy;
}
public void stop(){
x=0;
y=0;
}
public class Action implements ActionListener{
public void actionPerformed(ActionEvent e){
stop();
}
}
正如您在评论中看到的那样,我尝试了几种不同的技术,但都没有奏效。任何建议将不胜感激。谢谢
我得到的主要错误是:
non static field cannot be referenced from a static context
我认为那是因为我是从 main 方法运行它的。
Smart猫小萌
相关分类