0

运行以下代码时出现“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)

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

4

1 回答 1

3

你在该行得到一个 NullPointerException

sonuc.setText(""+sondurum);

在这一行有什么可能是 null 并导致这样的异常?答案:sonuc

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

代码中唯一引用的地方sonucinitialize()方法中:

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

这将创建一个与字段同名的局部sonuc变量。所以该字段sonuc永远不会被初始化。

将上面的行替换为

this.sonuc = new JLabel("Sonuç");
于 2013-07-18T10:55:30.750 回答