0

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?

mortalis
  • 2,060
  • 24
  • 34
Tetora
  • 1
  • 1
  • Could you post the code for your HeaderBar class please. Also, which line causes the NPE ? – jr593 May 10 '17 at 09:51
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Manish Kumar Sharma May 10 '17 at 09:52

1 Answers1

0

First of all, you should read What is a NullPointerException, and how do I fix it?.

Then, you should have looked the stacktrace which would have told you on which line the error occurred. It would have been useful to include it in your post.

Now, even without the stacktrace, I can assume that the NPE is caused by retrieve.txtarea.getText();. As you instanciated retrieve without setting any txtarea, I suppose that textarea is null, hence the NPE.

Community
  • 1
  • 1
Jeremy Grand
  • 2,300
  • 12
  • 18