gpt4 book ai didi

java - 当我尝试在 net-beans 中运行它时,我收到 "java.lang.reflect.InvocationTargetException"。为什么会发生这种情况?

转载 作者:行者123 更新时间:2023-12-02 05:23:34 26 4
gpt4 key购买 nike

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中运行时,小程序窗口正在显示,但没有像按钮一样可见的gui元素。在控制台中,我可以看到异常已被try catch block 捕获。为什么我会得到这个异常以及我该怎么做才能避免这种情况发生。

最佳答案

您没有看到 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();
}

关于java - 当我尝试在 net-beans 中运行它时,我收到 "java.lang.reflect.InvocationTargetException"。为什么会发生这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26278975/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com