I'm trying to get the text from JTextArea
stored into a variable which is then used in combination with FileWriter/BufferedWriter
to save the content in a file.
It works with a normal string like:
String stored = "Example";
But I always get a nullpointer exception error trying to use the following:
menuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
HeadBar retrieve = new HeadBar();
BufferedWriter bw = null;
try {
String stored = retrieve.txtarea.getText();
FileWriter fw = new FileWriter("H:/UserInput.txt");
bw = new BufferedWriter(fw);
bw.write(stored);
bw.flush();
System.out.println("Text saved successfully.");
} catch (IOException ex){
System.out.println("Error:" + ex.getMessage());
}
}
});
A part of Headbar
class in a method:
txtarea = new JTextArea();
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 800;
c.weighty = 5.0;
c.anchor = GridBagConstraints.CENTER;
c.gridx = 0;
c.gridwidth = 20;
c.gridy = 20;
panel.add(txtarea, c);
What did I do wrong or is getText()
the wrong method?