倒霉的Swing代码总是导致Exception, fatal error# Java - 爪哇娇娃
b*i
1 楼
下面main代码如果comment,则程序正常。否则每10次有大概一次出问题。咋回事?
theFrame=new JFrame();
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.setLayout(new BorderLayout()); // original border layout
textpane = new JTextArea(20,40);
textpane.setSize(300,300);
textpane.setText("Please wait for the main to load");
JScrollPane js=new JScrollPane(textpane);
theFrame.add(js, BorderLayout.PAGE_START);
theFrame.pack();
theFrame.setVisible(true);
其他地方,只有这里需要theFrame
if (condition never true when running){
theFrame.setVisible(true);
theFrame.toFront();
}
还有一个需要textpane的地方,在一个函数里,已经把直接调用swing改成invokeLater了
class TPAppender extends SwingInvoker{
String content;
TPAppender(String x){content=x;}
@Override
public void run() {
textpane.append(content);
}
}
System.out.println(x);
if (level if (textpane!=null){// the following line is causing java 6 to crash
(new TPAppender(x+"\n")).execute();//textpane.append(x+"\n");
}
}
下面是SwingInvoker
public abstract class SwingInvoker implements Runnable {
public void execute(){
if (SwingUtilities.isEventDispatchThread())
run();
else
SwingUtilities.invokeLater(this);
}
public void executeNow(){
if (SwingUtilities.isEventDispatchThread())
run();
else
try {
SwingUtilities.invokeAndWait(this);
} catch (Exception e) {
System.out.println("Error from invoker");
e.printStackTrace();
}
}
}
theFrame=new JFrame();
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.setLayout(new BorderLayout()); // original border layout
textpane = new JTextArea(20,40);
textpane.setSize(300,300);
textpane.setText("Please wait for the main to load");
JScrollPane js=new JScrollPane(textpane);
theFrame.add(js, BorderLayout.PAGE_START);
theFrame.pack();
theFrame.setVisible(true);
其他地方,只有这里需要theFrame
if (condition never true when running){
theFrame.setVisible(true);
theFrame.toFront();
}
还有一个需要textpane的地方,在一个函数里,已经把直接调用swing改成invokeLater了
class TPAppender extends SwingInvoker{
String content;
TPAppender(String x){content=x;}
@Override
public void run() {
textpane.append(content);
}
}
System.out.println(x);
if (level
(new TPAppender(x+"\n")).execute();//textpane.append(x+"\n");
}
}
下面是SwingInvoker
public abstract class SwingInvoker implements Runnable {
public void execute(){
if (SwingUtilities.isEventDispatchThread())
run();
else
SwingUtilities.invokeLater(this);
}
public void executeNow(){
if (SwingUtilities.isEventDispatchThread())
run();
else
try {
SwingUtilities.invokeAndWait(this);
} catch (Exception e) {
System.out.println("Error from invoker");
e.printStackTrace();
}
}
}