gpt4 book ai didi

java - 线程中 falseException 的代码错误

转载 作者:行者123 更新时间:2023-12-01 23:42:18 25 4
gpt4 key购买 nike

运行以下代码时出现“falseException”:

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingConstants;


public class deneme implements ActionListener {

private JFrame frmAsalTesti;
private JTextField yazi;
Sayi s1 =new Sayi();
String sondurum="";
JLabel sonuc;



/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
deneme window = new deneme();
window.frmAsalTesti.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the application.
*/
public deneme() {
initialize();
}

/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmAsalTesti = new JFrame();
frmAsalTesti.setTitle("Asal Testi");
frmAsalTesti.setResizable(false);
frmAsalTesti.setBounds(100, 100, 307, 167);
frmAsalTesti.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();
frmAsalTesti.getContentPane().add(panel, BorderLayout.CENTER);

JLabel lblDenemekIstediinizSayy = new JLabel("denemek istedi\u011Finiz say\u0131y\u0131 girin!");
panel.add(lblDenemekIstediinizSayy);

yazi = new JTextField();
yazi.setText("0");
panel.add(yazi);
yazi.setColumns(4);

JButton button = new JButton("Test Et");
panel.add(button);

JLabel sonuc = new JLabel("Sonuç");
panel.add(sonuc);
button.addActionListener(this);



}

@Override
public void actionPerformed(ActionEvent e) {
int gelen=0;
gelen=Integer.parseInt(yazi.getText());
System.out.println(s1.Asalmi(gelen));
if(s1.Asalmi(gelen))
{
sondurum="girilen sayı asaldır";
}
else
{
sondurum="girilen sayı asal değildir";
}

sonuc.setText(""+sondurum);

}



}

链接到行:sonuc.setText(""+sondurum);的错误是:

     falseException in thread "AWT-EventQueue-0" 
java.lang.NullPointerException
at deneme.actionPerformed(deneme.java:94)

我找不到解决方案,正在等待您的答复。我只想更改标签,使其成为动态标签。

最佳答案

您在该行收到 NullPointerException

sonuc.setText(""+sondurum);

这一行什么可能为空并导致这样的异常?答案:sonuc

那么,sonuc 是否在某处初始化了?

代码中唯一引用 sonuc 的地方是 initialize() 方法:

JLabel sonuc = new JLabel("Sonuç");

这将创建一个与字段 sonuc 同名的本地变量。因此字段 sonuc 永远不会被初始化。

将上面的行替换为

this.sonuc = new JLabel("Sonuç");

关于java - 线程中 falseException 的代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17721182/

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