Chapter 11.3.3 – Files in GUI Programs | Introduction to Programming Using Java
11.3.3 Files in GUI Programs
The previous examples in this section use a command-line interface, but graphical user interface programs can also manipulate files. Programs typically have an “Open” command that reads the data from a file and displays it in a window and a “Save” command that writes the data from the window into a file.
We can illustrate this in Java with a simple text editor program, TrivialEdit.java. The window for this program uses a JTextArea component to display some text that the user can edit. It also has a menu bar, with a “File” menu that includes “Open” and “Save” commands. These commands are implemented using the techniques for reading and writing files that were covered in Section 11.2.
When the user selects the Open command from the File menu in the TrivialEdit program, the program pops up a file dialog box where the user specifies the file. It is assumed that the file is a text file. A limit of 10000 characters is put on the size of the file, since a JTextArea is not meant for editing large amounts of text.
The program reads the text contained in the specified file, and sets that text to be the content of the JTextArea. In this case, I decided to use a BufferedReader to read the file line-by-line. The program also sets the title bar of the window to show the name of the file that was opened. All this is done in the following method, which is just a variation of the readFile() method presented in Section 11.2:
In this program, the instance variable editFile is used to keep track of the file that is currently being edited, if any, and the setTitle() method (from class JFrame) is used to set the title of the window to show the name of the file.
Similarly, the response to the Save command is a minor variation on the writeFile() method from Section 11.2. I will not repeat it here. If you would like to see the entire program, you will find the source code in the file TrivialEdit.java.
SEE MORE:
- Chapter 11.4 Networking | Introduction to Programming Using Java
- Chapter 11.4.2 TCP/IP and Client/Server | Introduction to Program ming Using Java
- Chapter 11.4.4 A Trivial Client/Server | Introduction to Programming Using Java
- Chapter 11.5 Network Programming and Threads | Introduction to Programming Using Java
- Chapter 11.5.1 A Threaded GUI Chat Program | Introduction to Programming Using Java
- Chapter 11.5.2 A Multithreaded Server | Introduction to Program ming Using Java
- Chapter 11.6.2 XMLEncoder and XMLDecoder | Introduction to Program’ming Using Java
- Chapter 11.6.3 Working With the DOM | Introduction to Program ming Using Java
- Exercises for Chapter 11 | Introduction to Programming Using Java
- Chapter 12 Advanced GUI Programming | Images and Resources | Introduction to Program ming Using Java
26 thoughts on “Chapter 11.3.3 – Files in GUI Programs | Introduction to Programming Using Java”