我正在创造一个巨魔'就像在YouTube视频中使用的应用程序一样,我希望JFrame每1/2秒在屏幕上跳转一次。
继承我的代码:
package troll1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.Timer;
public class troll extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
public static void main(String args[]) {
troll w1 = new troll();
w1.setVisible(true);
w1.setSize(500,500);
}
public Random ran;
public int random;
public troll w1;
public Timer t;
public troll() {
Timer t = new Timer(500, this);
t.start();
}
@Override
public void actionPerformed(ActionEvent arg0) {
Random ran = new Random();
for(int counter=1; counter<=1;counter++) {
int random = 1+ran.nextInt(500);
w1.setLocation(random, random);
}
}
}
问题是,当我运行此代码时,我收到错误消息
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at troll1.troll.actionPerformed(troll.java:37)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
此外,一旦我的错误消失了,我就会这样做,以便JFrame在整个屏幕上跳跃,而不仅仅是500,500及以下。
答案 0 :(得分:0)
w1变量始终为null永远不会被赋值。你可以在actionPerformed中使用它来使它以这种方式工作
@Override
public void actionPerformed(ActionEvent arg0) {
Random ran = new Random();
for(int counter=1; counter<=1;counter++) {
int random = 1+ran.nextInt(500);
this.setLocation(random, random);
}
}