运行以下代码时出现“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)
我找不到解决方案而且我在等你的答案。我只想更改标签,使其成为动态标签。
答案 0 :(得分:3)
您在
行获得NullPointerExceptionsonuc.setText(""+sondurum);
此行可能为null并导致此类异常?答案:sonuc
。
那么,sonuc
是否在某处初始化了?
代码中引用sonuc
的唯一位置是initialize()
方法:
JLabel sonuc = new JLabel("Sonuç");
这会创建一个 local 变量,其名称与字段sonuc
相同。因此,字段sonuc
永远不会被初始化。
将上述行替换为
this.sonuc = new JLabel("Sonuç");