File Tutorial AP Computer Science 2005-2006

Create the above JFrame GUI with a JTextArea, two JLabels, and 2 JButtons.

This program will write a text file to disk, read a text file from disk, and display the contents of the file. The file can also be viewed or written with Notepad or any word processor using a .txt extension.

Note the \\ in the filenames. Recall \ is the "escape" character (\n, \t, etc.). The sequence \\ is needed to indicate you are not using an escape sequence.

If you just enter a filename instead of an absolute pathname, the file is written to the current directory (i.e., your NetBeans project directory).

I also write setLocationRelativeTo(null); after initComponents( ); in the GUI constructor.

private void jOpenButtonActionPerformed(java.awt.event.ActionEvent evt) {

String fileName = "C:\\Documents and Settings\\Curt\\
My Documents\\School\\2005-2006 courses\\Java\\myText.txt" ;

String line;

String output = "";

Scanner input;

try

{

input = new Scanner(new File( fileName ));

do

{

line = input.nextLine( );

output += line + "\n";

} while ( input.hasNext( ) );

jInputTextArea.setText(output);

input.close();

}

catch ( IOException iox )

{

System.out.println("Problem reading " + fileName );

}

}

private void jSaveButtonActionPerformed(java.awt.event.ActionEvent evt) {

String input = jInputTextArea.getText( );

String fileName = "C:\\Documents and Settings\\Curt\\

My Documents\\School\\2005-2006 courses\\Java\\myText.txt";

try

{

FileWriter writer = new FileWriter( fileName );

writer.write( input );

jInputTextArea.setText("");

writer.close();

}

catch ( IOException iox )

{

System.out.println("Problem writing " + fileName );

}

}


Using JFileChooser

To open and save files without hard-coding the file name or asking the user to enter the name, use JFileChooser. The program below write, reads, and displays text files using JFileChoosers to select the files.

private void jOpenButtonActionPerformed(java.awt.event.ActionEvent evt) {

JFileChooser fileChooser = new JFileChooser( );

int result = fileChooser.showOpenDialog( this );

if( result == JFileChooser.CANCEL_OPTION)

return;

File fileName = fileChooser.getSelectedFile( );

String line;

String output = "";

Scanner input;

try

{

input = new Scanner(new File( fileName.getCanonicalPath( ) ));

do

{

line = input.nextLine( );

output += line + "\n";

} while ( input.hasNext( ) );

jTextArea.setText(output);

input.close();

}

catch ( IOException iox )

{

System.out.println("Problem reading " + fileName );

}

}

private void jSaveButtonActionPerformed(java.awt.event.ActionEvent evt) {

String input = jTextArea.getText( );

JFileChooser fileChooser = new JFileChooser( );

int result = fileChooser.showSaveDialog( this );

if( result == JFileChooser.CANCEL_OPTION)

return;

File fileName = fileChooser.getSelectedFile( );

PrintWriter outFile;

try

{

outFile = new PrintWriter(new FileWriter(fileName));

}

catch (IOException e)

{

return;

}

outFile.print(input);

outFile.close( );

}


/*

* GiftListGUI.java

*

* Created on November 12, 2005, 4:14 PM

*/

package GiftList;

import javax.swing.*;

import java.awt.*;

import java.util.*;

import java.io.*;

/**

*

* @author Curtis Watson

*/

public class GiftListGUI extends javax.swing.JFrame {

ArrayList list = new ArrayList(100);

/** Creates new form GiftListGUI */

public GiftListGUI() {

initComponents();

jDeletePanel.setVisible(false);

jAddPanel.setVisible(false);

setLocationRelativeTo(null);

}

/** This method is called from within the constructor to

* initialize the form.

* WARNING: Do NOT modify this code. The content of this method is

* always regenerated by the Form Editor.

*/

// <editor-fold defaultstate="collapsed" desc=" Generated Code ">

private void initComponents() {

buttonGroup1 = new javax.swing.ButtonGroup();

jTabbedPane1 = new javax.swing.JTabbedPane();

jMenuPanel = new javax.swing.JPanel();

jLabel1 = new javax.swing.JLabel();

jCreatePanel = new javax.swing.JPanel();

jLabel2 = new javax.swing.JLabel();

jLabel3 = new javax.swing.JLabel();

jLabel4 = new javax.swing.JLabel();

jFirstNameField = new javax.swing.JTextField();

jLastNameField = new javax.swing.JTextField();

jGiftRequestedField = new javax.swing.JTextField();

jCreateButton = new javax.swing.JButton();

jViewPanel = new javax.swing.JPanel();

jListArea = new javax.swing.JTextArea();

jViewButton = new javax.swing.JButton();

jPrintButton = new javax.swing.JButton();

jEditPanel = new javax.swing.JPanel();

jRadioPanel = new javax.swing.JPanel();

jDeleteRadio = new javax.swing.JRadioButton();

jModifyRadio = new javax.swing.JRadioButton();

jAddRadio = new javax.swing.JRadioButton();

jDeletePanel = new javax.swing.JPanel();

jLabel5 = new javax.swing.JLabel();

jIDtoDeleteField = new javax.swing.JTextField();

jDeleteButton = new javax.swing.JButton();

jAddPanel = new javax.swing.JPanel();

jLabel6 = new javax.swing.JLabel();

jLabel7 = new javax.swing.JLabel();

jLabel8 = new javax.swing.JLabel();

jNameFirstField = new javax.swing.JTextField();

jNameSecondField = new javax.swing.JTextField();

jRequestedGiftField = new javax.swing.JTextField();

jUpdateButton = new javax.swing.JButton();

jScrollPane1 = new javax.swing.JScrollPane();

jDisplayArea = new javax.swing.JTextArea();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jTabbedPane1.setMinimumSize(new java.awt.Dimension(340, 565));

jTabbedPane1.setPreferredSize(new java.awt.Dimension(340, 565));

jMenuPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

jMenuPanel.setMinimumSize(new java.awt.Dimension(338, 566));

jMenuPanel.setPreferredSize(new java.awt.Dimension(338, 566));

jLabel1.setIcon(new javax.swing.ImageIcon("C:\\JavaPrograms\\FileExample\\opusSanta.jpg"));

jLabel1.setMaximumSize(new java.awt.Dimension(338, 566));

jLabel1.setMinimumSize(new java.awt.Dimension(338, 566));

jLabel1.setOpaque(true);

jLabel1.setPreferredSize(new java.awt.Dimension(338, 565));

jMenuPanel.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));

jTabbedPane1.addTab("Gift List Home", jMenuPanel);

jCreatePanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

jLabel2.setText("First Name");

jCreatePanel.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 50, -1, -1));

jLabel3.setText("Last Name");

jCreatePanel.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 100, -1, -1));

jLabel4.setText("Gift Requested");

jCreatePanel.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 150, -1, -1));

jCreatePanel.add(jFirstNameField, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 50, 150, -1));

jCreatePanel.add(jLastNameField, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 100, 150, -1));

jCreatePanel.add(jGiftRequestedField, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 150, 150, -1));

jCreateButton.setBackground(new java.awt.Color(255, 255, 255));

jCreateButton.setFont(new java.awt.Font("Tahoma", 1, 11));

jCreateButton.setForeground(new java.awt.Color(255, 0, 51));

jCreateButton.setIcon(new javax.swing.ImageIcon("C:\\JavaPrograms\\FileExample\\xmasTree.jpg"));

jCreateButton.setText("Click to Add Recipient to List");

jCreateButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

jCreateButton.setIconTextGap(0);

jCreateButton.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);

jCreateButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

jCreateButton.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jCreateButtonActionPerformed(evt);

}

});

jCreatePanel.add(jCreateButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 200, -1, -1));

jTabbedPane1.addTab("Create List", jCreatePanel);

jViewPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

jListArea.setColumns(20);

jListArea.setRows(20);

jListArea.setMinimumSize(new java.awt.Dimension(300, 450));

jListArea.setPreferredSize(new java.awt.Dimension(300, 450));

jViewPanel.add(jListArea, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, -1, -1));

jViewButton.setText("View List");

jViewButton.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jViewButtonActionPerformed(evt);

}

});

jViewPanel.add(jViewButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 500, -1, -1));

jPrintButton.setText("Print List");

jPrintButton.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jPrintButtonActionPerformed(evt);

}

});

jViewPanel.add(jPrintButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 500, -1, -1));

jTabbedPane1.addTab("View List", jViewPanel);

jEditPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

jEditPanel.setMinimumSize(new java.awt.Dimension(340, 565));

jEditPanel.setPreferredSize(new java.awt.Dimension(340, 565));

jRadioPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

jRadioPanel.setBorder(new javax.swing.border.TitledBorder("Select an Editing Option"));

buttonGroup1.add(jDeleteRadio);

jDeleteRadio.setText("Delete a record");

jDeleteRadio.addItemListener(new java.awt.event.ItemListener() {

public void itemStateChanged(java.awt.event.ItemEvent evt) {

jDeleteRadioItemStateChanged(evt);

}

});

jRadioPanel.add(jDeleteRadio, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, -1, -1));

buttonGroup1.add(jModifyRadio);

jModifyRadio.setText("Modify a record");

jModifyRadio.addItemListener(new java.awt.event.ItemListener() {

public void itemStateChanged(java.awt.event.ItemEvent evt) {

jModifyRadioItemStateChanged(evt);

}

});

jRadioPanel.add(jModifyRadio, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 60, 140, -1));

buttonGroup1.add(jAddRadio);

jAddRadio.setText("Add new record");

jAddRadio.addItemListener(new java.awt.event.ItemListener() {

public void itemStateChanged(java.awt.event.ItemEvent evt) {

jAddRadioItemStateChanged(evt);

}

});

jRadioPanel.add(jAddRadio, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, -1, -1));

jEditPanel.add(jRadioPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, 160, 140));

jDeletePanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

jDeletePanel.setBorder(new javax.swing.border.TitledBorder("Delete Option"));

jLabel5.setText("Enter ID to delete");

jDeletePanel.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 110, -1));

jDeletePanel.add(jIDtoDeleteField, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 60, 30, -1));

jDeleteButton.setText("Delete");

jDeleteButton.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jDeleteButtonActionPerformed(evt);

}

});

jDeletePanel.add(jDeleteButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, -1, -1));

jEditPanel.add(jDeletePanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 30, 130, 140));

jAddPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

jAddPanel.setBorder(new javax.swing.border.TitledBorder("Add/Modify Option"));

jLabel6.setText("First Name");

jAddPanel.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, -1, -1));

jLabel7.setText("Last Name");

jAddPanel.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, -1, -1));

jLabel8.setText("Gift Requested");

jAddPanel.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 110, -1, -1));

jAddPanel.add(jNameFirstField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 30, 60, -1));

jAddPanel.add(jNameSecondField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 70, 60, -1));

jAddPanel.add(jRequestedGiftField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 110, 60, -1));

jUpdateButton.setText("Update");

jAddPanel.add(jUpdateButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 20, 80, 110));

jEditPanel.add(jAddPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 200, 300, 150));

jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

jScrollPane1.setPreferredSize(new java.awt.Dimension(300, 102));

jScrollPane1.setViewport(null);

jDisplayArea.setMinimumSize(new java.awt.Dimension(280, 100));

jDisplayArea.setPreferredSize(new java.awt.Dimension(280, 100));

jScrollPane1.setViewportView(jDisplayArea);

jEditPanel.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 390, -1, 120));

jTabbedPane1.addTab("Edit List", jEditPanel);

getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER);

pack();

}

// </editor-fold>

private void jAddRadioItemStateChanged(java.awt.event.ItemEvent evt) {

// TODO add your handling code here:

displayList( );

if(jAddRadio.isSelected( ))

{

jAddPanel.setVisible(true);

myAddMethod( );

}

else

{

jAddPanel.setVisible(false);

}

}

private void jModifyRadioItemStateChanged(java.awt.event.ItemEvent evt) {

// TODO add your handling code here:

displayList( );

if(jModifyRadio.isSelected( ))

{

jAddPanel.setVisible(true);

myModifyMethod( );

}

else

{

jAddPanel.setVisible(false);

}

}

private void jDeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {

myDeleteMethod( );

//jIDtoDeleteField.setText("");

}

private void jDeleteRadioItemStateChanged(java.awt.event.ItemEvent evt) {

// TODO add your handling code here:

displayList( );

if(jDeleteRadio.isSelected( ))

{

jDeletePanel.setVisible(true);

}

else

{

jDeletePanel.setVisible(false);

}

}

private void myDeleteMethod( )

{

readList( );

displayList( );

int item = Integer.parseInt(jIDtoDeleteField.getText( ));

for(int i = 0; i < list.size( ); i++)

{

}

}

private void myAddMethod( )

{

}

private void myModifyMethod( )

{

}

private void readList( )

{

String fileName = "C:\\JavaPrograms\\FileExample\\gifts.txt" ;

String line;

String output = "";

Scanner input;

try

{

input = new Scanner(new File( fileName ));

do

{

line = input.nextLine( );

list.add(line);

output += line + "\n";

} while ( input.hasNextLine( ) );

jDisplayArea.setText(output);

input.close();

}

catch ( IOException iox )

{

System.out.println("Problem reading " + fileName );

}

}

private void writeList( )

{

File fileName = new File("C:\\JavaPrograms\\FileExample\\gifts.txt");

PrintWriter outFile;

try

{

outFile = new PrintWriter(new FileWriter(fileName, true));

}

catch (IOException e)

{

System.out.println("Error writing");

return;

}

for(int j = 0; j < list.size( ); j++)

{

outFile.println(list.get(j));

}

outFile.flush( );

outFile.close( );

}

private void displayList( )

{

readList( );

jDisplayArea.setText("");

for(int k = 0; k < list.size( ); k++)

{

jDisplayArea.append((String)list.get(k) + "\n");

}

}

private void jViewButtonActionPerformed(java.awt.event.ActionEvent evt) {

String fileName = "C:\\JavaPrograms\\FileExample\\gifts.txt" ;

String line;

String output = "";

Scanner input;

jListArea.setText("");

try

{

input = new Scanner(new File( fileName ));

do

{

line = input.nextLine( );

output += line + "\n";

} while ( input.hasNextLine( ) );

jListArea.setText(output);

input.close();

}

catch ( IOException iox )

{

System.out.println("Problem reading " + fileName );

}

}

private void jPrintButtonActionPerformed(java.awt.event.ActionEvent evt) {

PrintUtilities.printComponent(this);

}

private void jCreateButtonActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

String fname = jFirstNameField.getText( );

String lname = jLastNameField.getText( );

String gift = jGiftRequestedField.getText( );

File fileName = new File("C:\\JavaPrograms\\FileExample\\gifts.txt");

PrintWriter outFile;

try

{

outFile = new PrintWriter(new FileWriter(fileName, true));

}

catch (IOException e)

{

System.out.println("Error writing");

return;

}

Recipient r = new Recipient(fname, lname, gift);

outFile.println(r);

outFile.flush( );

outFile.close( );

jFirstNameField.setText("");

jLastNameField.setText("");

jGiftRequestedField.setText("");

jFirstNameField.requestFocus( );

}

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new GiftListGUI().setVisible(true);

}

});

}

// Variables declaration - do not modify

private javax.swing.ButtonGroup buttonGroup1;

private javax.swing.JPanel jAddPanel;

private javax.swing.JRadioButton jAddRadio;

private javax.swing.JButton jCreateButton;

private javax.swing.JPanel jCreatePanel;

private javax.swing.JButton jDeleteButton;

private javax.swing.JPanel jDeletePanel;

private javax.swing.JRadioButton jDeleteRadio;

private javax.swing.JTextArea jDisplayArea;

private javax.swing.JPanel jEditPanel;

private javax.swing.JTextField jFirstNameField;

private javax.swing.JTextField jGiftRequestedField;

private javax.swing.JTextField jIDtoDeleteField;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

private javax.swing.JLabel jLabel3;

private javax.swing.JLabel jLabel4;

private javax.swing.JLabel jLabel5;

private javax.swing.JLabel jLabel6;

private javax.swing.JLabel jLabel7;

private javax.swing.JLabel jLabel8;

private javax.swing.JTextField jLastNameField;

private javax.swing.JTextArea jListArea;

private javax.swing.JPanel jMenuPanel;

private javax.swing.JRadioButton jModifyRadio;

private javax.swing.JTextField jNameFirstField;

private javax.swing.JTextField jNameSecondField;

private javax.swing.JButton jPrintButton;

private javax.swing.JPanel jRadioPanel;

private javax.swing.JTextField jRequestedGiftField;

private javax.swing.JScrollPane jScrollPane1;

private javax.swing.JTabbedPane jTabbedPane1;

private javax.swing.JButton jUpdateButton;

private javax.swing.JButton jViewButton;

private javax.swing.JPanel jViewPanel;

// End of variables declaration

}

5