这段代码出了什么问题?

Joh*_*nna 1 java swing nullpointerexception

我写了这段代码:

public class FileViewer extends JPanel implements ActionListener {

/**
 * 
 */
private static final long serialVersionUID = 1L;

JFileChooser chooser;

FileNameExtensionFilter filter = null;

JEditorPane pane = null;

JTextField text = null;

JButton button;

JTextArea o = null;

URL url;

public FileViewer(JTextArea o) {
    this.o = o;
    setLayout(new FlowLayout(FlowLayout.RIGHT));
    JTextField text = new JTextField("file...", 31);
    text.setColumns(45);
    text.revalidate();
    text.setEditable(true);

    button = new JButton("Browse");
    add(text);
    add(button);
    filter = new FileNameExtensionFilter("html", "html");
    chooser = new JFileChooser();
    chooser.addChoosableFileFilter(filter);

    button.addActionListener(this);

}

public void paintComponent(Graphics g) {
    super.paintComponents(g);
    Graphics2D graphic = (Graphics2D) g;
    graphic.drawString("HTML File:", 10, 20);

}

public void actionPerformed(ActionEvent event) {
    int returnVal = 0;
    if (event.getSource() == button) {
        returnVal = chooser.showOpenDialog(FileViewer.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            text.setToolTipText(chooser.getSelectedFile().getName());

        } else
            o.append("Open command cancled by user.");
      }
     }
}
Run Code Online (Sandbox Code Playgroud)

但是在行中:text.setToolTipText(chooser.getSelectedFile().getName());抛出了NullPointerException!

编辑 我已经解决了我上面提到的问题,但它无法正常工作(它没有在文本中写出文件的名称!):-(

Mer*_*son 13

您已text全局声明并已分配NULL给它.在您的构造函数中,FileViewer您再次声明它new,但此声明是本地的.引用的变量actionPerformed()是全局变量,它仍然是NULL,所以你得到了异常.如果你改变了

JTextField text = new JTextField("file...", 31);
Run Code Online (Sandbox Code Playgroud)

text = new JTextField("file...", 31);
Run Code Online (Sandbox Code Playgroud)

应该修复它.