What's wrong with this code? [closed]
-
11-09-2019 - |
Question
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!) :-(
Solution
Answering your other point:
text.setToolTipText(chooser.getSelectedFile().getName());
Was this the intended behaviour? The filename will only appear as a tooltip when you mouse over the text field. To put text directly into a JTextField you should call setText()
instead.
OTHER TIPS
You've declared text
globally and assigned NULL
to it. In your constructor for FileViewer
you declare it again with new
, but this declaration is local. The variable referenced in actionPerformed()
is the global one, which is still NULL
, so you get the exception. If you change
JTextField text = new JTextField("file...", 31);
to
text = new JTextField("file...", 31);
that should fix it.
replace this:
JTextField text = new JTextField("file...", 31);
with this:
text = new JTextField("file...", 31);
The field text is null as in your FileViewer constructor you have created a local variable called text that has been added to the form.
Replace
JTextField text = new JTextField("file...", 31);
with
text = new JTextField("file...", 31);
setToolTipText
method does not set the text. It sets the tooltip text, which is shown when mouse hovers the text. Use setText
method.