Chapter 11.3.3 – Files in GUI Programs | Introduction to Programming Using Java

Chapter 11.3.3 – Files in GUI Programs | Introduction to Programming Using Java

 

11.3.3 Files in GUI Programs

 

Chapter 11.3.3 Files in GUI Programs | Introduction to Programming Using Java

 

 

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.

 

 

Chapter 11.3.3 - Files in GUI Programs | Introduction to Programming Using Java

 

 

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:

 

Chapter 11.3.3 - Files in GUI Programs | Introduction to Programming Using Java

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.

 

 

Chapter 11.3.3 - Files in GUI Programs | Introduction to Programming Using Java

 

 

 

 

SEE MORE:

 

26 thoughts on “Chapter 11.3.3 – Files in GUI Programs | Introduction to Programming Using Java”

Leave a Comment