我有一个Swing计划。我无法将整个主类保存到文件中。
public class GreenHouseMain extends JFrame implements ActionListener,
MouseListener, Runnable, WindowListener, KeyListener, Serializable
{
//.....other components
static GreenHouseMain ghMain;
}
public static void main(String[] args)
{
ghMain = new GreenHouseMain();
}
public void startEvents()
{
suspended = false;
terminate = false;
jbStart.setEnabled(false);
worker = new Thread(new Runnable()
{
public void run()
{
try
{
//Other Code
} catch (ControllerException e)
{
try
{
Date now = new Date();
String log = "";
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("error.log")));
if (e.getMessage() == "Unknown Windows Malfuction")
{
log = "ErrorCode=1, WindowMalfunction," + now;
} else
{
log = "ErrorCode=2, PowerOut," + now;
}
out.println(log);
jTextArea.append(log + "\n");
out.close();
out.flush();
ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream("dump.out"));
//It failed in here, says "java.lang.NullPointerException
output.writeObject(GreenHouseMain.ghMain);
output.flush();
} catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
});
worker.start();
}
你应该知道几件事: 1.所有类都已实现Serializable接口 2.程序中有几个线程(不知道是否是异常的原因 3.我已经使用序列化了一个对象来提交大约相同的代码,但是在控制台应用程序中。不知道为什么它在这里失败。
at javax.swing.plaf.basic.BasicScrollPaneUI.paint(Unknown Source) 在javax.swing.plaf.ComponentUI.update(未知来源) 在javax.swing.JComponent.paintComponent(未知来源) 在javax.swing.JComponent.paint(未知来源) 在javax.swing.JComponent.paintToOffscreen(未知来源) 在javax.swing.RepaintManager $ PaintManager.paintDoubleBuffered(未知来源) 在javax.swing.RepaintManager $ PaintManager.paint(未知来源) 在javax.swing.RepaintManager.paint(未知来源) 在javax.swing.JComponent._paintImmediately(未知来源) 在javax.swing.JComponent.paintImmediately(未知来源) 在javax.swing.RepaintManager.paintDirtyRegions(未知来源) 在javax.swing.RepaintManager.paintDirtyRegions(未知来源) 在javax.swing.RepaintManager.seqPaintDirtyRegions(未知来源) at javax.swing.SystemEventQueueUtilities $ ComponentWorkRequest.run(Unknown Source) at java.awt.event.InvocationEvent.dispatch(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) 在java.awt.EventDispatchThread.run(未知来源)
答案 0 :(得分:1)
此
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
应该是:
} catch (IOException ex) {
ex.printStackTrace();
}
这将为您提供更多更好的信息,最重要的是发生NullPointerException的确切行以及到达该行的位置。如果这不能解决问题的原因,请在调试器中启动程序并在该行上放置断点。