- 论坛徽章:
- 0
|
测试代码:
package com.test.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class TestTimer extends JFrame implements ActionListener {
private static final long serialVersionUID = -7533926242538206319L;
Timer timer;
private JTextField send;
private JTextArea reply;
public TestTimer() {
super("Test Send");
setSize(300, 300);
timer = new Timer();
timer.schedule(new ScheduleRunTask(), 0, 1 * 60000);
send = new JTextField();
getContentPane().add(send, "South");
send.addActionListener(this);
reply = new JTextArea(8, 40);
reply.setEditable(false);
JScrollPane scrollPane = new JScrollPane(reply);
getContentPane().add(scrollPane, "Center");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void stop() {
timer.cancel();
}
class ScheduleRunTask extends TimerTask {
public void runCheckAutobahnFXAPITask() {
TestTimer.this.reply.append("Test\n");
}
public void run() {
System.out.println("run()");
runCheckAutobahnFXAPITask();
}
}
public static void main(String[] args) {
JFrame frame = new TestTimer();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == send) {
reply.append(send.getText() + "\n");
send.setText("");
}
}
public JTextArea getReply() {
return reply;
}
public void setReply(JTextArea reply) {
this.reply = reply;
}
}
|
运行结果:
run()
Exception in thread "Timer-0" java.lang.NullPointerException
at com.test.gui.TestTimer$ScheduleRunTask.runCheckAutobahnFXAPITask(TestTimer.java:55)
at com.test.gui.TestTimer$ScheduleRunTask.run(TestTimer.java:60)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
毛病出在这一行:
TestTimer.this.reply.append("Test\n");
而这个是可以直接使用外部类的成员的:
package com.test.general;
class Outer {
private int index = 100;
class Inner {
private int index = 50;
void print() {
int index = 30;
System.out.println(index); // 30
System.out.println(this.index); // 50
System.out.println(Outer.this.index); // 100
}
}
void print() {
index = 101;
Inner inner = new Inner();
inner.print();
}
public static void main(String[] args) {
Outer outer = new Outer();
outer.print();
}
}
|
请问哪位给些指点? |
|