这段java为什么会报空指针异常?

来源:百度知道 编辑:UC知道 时间:2024/05/12 18:40:25
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
public class Encoding implements ActionListener {
private JFrame f;
private JTextField jtff;
private JTextField jtfc;
private JTextField jtfn;
// private JScrollPane jsp;
private JButton jb;
private JButton jbs;
private Font font;
private JPanel jp1;
private JPanel jp2;
private JPanel jp3;
private JPanel jp4;
private JLabel jl1;
private JLabel jl2;
private JLabel jl3;
private JRadioButton jrb1;
private JRadioButton jrb2;

public void init() { // 初始化面板
/** 生成各组件的对象* */
f = new JFrame("凯文炫文件加密器 V0.1");
f.setLayout(new GridLayout(4, 1));
jtff = new JTextField(25); // 选择器
jtfc = new JTextField(25);// 加密算子
jtfn = new JTextField(10);// 重命名窗口
jb = new JButton("加密");
jbs = new JButton("选择文件");

问题出在这里:
/** 添加监听器* */

Encoding listener = new Encoding();

jtfc.addActionListener(listener);
jtfn.addActionListener(listener);
jb.addActionListener(listener);
jbs.addActionListener(listener);
jrb1.addActionListener(listener);
jrb2.addActionListener(listener);
------------------------------
原因:Encoding 本身是一个ActionListener,jtfc都在本身 的Encoding 中,Encoding listener = new Encoding();这句话,生成了一个新的ActionListener,导致了jtfc等一干控件都去监听了这个新的ActionListener了,所以会导致空指针,只要改成下面的代码就行了:
//Encoding listener = new Encoding();这句话要注释掉
jtfc.addActionListener(this);
jtfn.addActionListener(this);
jb.addActionListener(this);
jbs.addActionListener(this);
jrb1.addActionListener(this);
jrb2.addActionListener(this);

path 里没内容啊 为null
判断下 if(path==null)就不执行下句