I wrote this code:
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.");
}
}
}
But in the line: text.setToolTipText(chooser.getSelectedFile().getName());
a NullPointerException is thrown!
EDIT I have fixed the problem which I have mentioned above but it doesn't work correctly (it doesn't write the name of the file in the text!) :-(