Reputation: 1138
I have a JTextArea on a JFrame and a JButton.
When user types characters on the JTextArea textArea and presses the button, I want the information to be saved in a textFile.
JTextArea textArea = new JTextArea(2, 20);
textArea.setLineWrap (true);
thehandler4 handler4 = new thehandler4(); // next button
button4.addActionListener(handler4);
private class thehandler4 implements ActionListener{ //next button
public void actionPerformed(ActionEvent event){
PrintWriter log = null;
try {
FileWriter logg =new FileWriter("logsheet.txt",true);
log = new PrintWriter(logg);
log.println("Quick Notes: "+textArea);
log.close();
} catch( Exception y ) { y.printStackTrace(); }
}}
But when I open the logsheet.txt, I don't see any thing. its null. is there a function I need like textArea.getText(); i tried that but I get an error.
Upvotes: 1
Views: 14300
Reputation: 324197
I'm guessing your problem is that you have your text area defined as a class varaible and a local variable. Your ActionListener is accessing the class variable which is null.
//JTextArea textArea = new JTextArea(2, 20); // this is wrong, you don't want a local variable
textArea = new JTextArea(2, 20);
Also, using the textArea.write(...) method is the proper way to do this. You don't want to use the getText() method, because that approach may result in the wrong newline characters being contained in the string.
Upvotes: 3
Reputation: 30395
You could do the following instead:
JTextArea textArea = new JTextArea(2, 20);
FileWriter logg =new FileWriter("logsheet.txt",true);
textArea.write(logg);
The write() method allows you to write text from text area to a writer.
Upvotes: 0