当我尝试在net-beans中运行它时,我得到一个“java.lang.reflect.InvocationTargetException”。为什么会这样?

时间:2014-10-09 12:54:55

标签: java swing exception jvm japplet

package airlinep;

/**
 *
 * 
 */
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
public class NewClass1 extends JApplet{
JButton b1; 
  JButton b2; 

  JLabel lbl; 
    @Override
    public void init()
    {
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run(){
                guiInit();//throw new UnsupportedOperationException("Not supported yet."); 
            }
        }); 
    } catch (Exception ex) {
        System.out.println("could not generate due to "+ex.toString());
    } 
    }

public void start()
{}
public void stop()
{}
public void destroy()
{}
private void guiInit()
{
//setLayout(new FlowLayout());
b1.setText("b1");
b2.setText("b2");
b1.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent ae) {
         lbl.setText(b1.getText()+" was pressed at ");//To change body of generated methods, choose Tools | Templates.
    }
});
b2.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent ae) {
         lbl.setText(b2.getText()+" was pressed at ");//To change body of generated methods, choose Tools | Templates.
    }
});
getContentPane().add(b1);
getContentPane().add(b2);
getContentPane().add(lbl);
}
}

当程序在netbeans中运行时,applet窗口显示但是没有gui元素看不到像buttons.and在控制台中我可以看到try catch块已经捕获到异常。为什么我得到这个例外,我可以做什么,以免发生这种情况。

1 个答案:

答案 0 :(得分:2)

你有一个你没有看到的NullPointerException,因为你没有正确捕获异常。您必须为参考变量分配对象,包括JButton和JLabel变量,之前尝试使用它们。

换句话说,改变

JButton b1; 
JButton b2; 

JLabel lbl; 

JButton b1 = new JButton("something"); 
JButton b2 = new JButton("something else"); 

JLabel lbl = new JLabel("something else entirely"); 

同样要捕获错过的目标异常,请考虑:

  try {
     SwingUtilities.invokeAndWait(new Runnable() {
        @Override
        public void run() {
           guiInit();
        }
     });
  } catch (InvocationTargetException e) {
     e.getTargetException().printStackTrace(); // get the target exception
  } catch (InterruptedException e) {
     e.printStackTrace();
  }