Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JTextArea append() not working?

 
Jon Mattson
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So I'm planning to make a level editor for a game and to do that I must be able to read and save files. Now I'm making a program that opens a textfile and shows the text in a JTextArea but the append() method doesn't work where it's supposed to. It seems it stops working after I opened a dialog with filechooser. So what's wrong?

Here's the code:

 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Each time you call createContentPane(), a new JTextArea is created and the member variable "log" set to point to it. The original one is still on the screen, but "log" isn't referring to it anymore. You're then appending to another JTextArea that isn't visible!

I don't understand why you're calling this method repeatedly, when you've got a member variable to refer to everything else; just store the return value the very first time you call it into a member, and use that member everywhere else.
 
Jon Mattson
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sweet it's working now, thx alot

Now I've been trying to make it able to save the text. I wrote some code but it doesn't seem to work. It saves a file but it's empty. If I load a file and save it without changing anything it works.

Here is the code:


I also tried using PrintWriters methods print(string) and write(string) but they didn't work either.
 
Paul Clapham
Sheriff
Posts: 21322
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You didn't close the writer after you finished using it. Since writing to disk files happens in chunks of several K bytes at a time (because that's how the operating system deals with files), you're losing the last chunk. Which is probably the whole thing. Close the writer in a finally block like this:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic