使用文件i / o将数据写入jTable

时间:2013-03-15 18:09:20

标签: java swing file-io arraylist jtable

请您查看我的代码并解释为什么我的程序会在数组列表中写入更多条目?

package pkg842994_ranganathan_vocabtrainerdossier;
import javax.swing.JLabel;
import javax.swing.JFrame;
import java.util.ArrayList;
import javax.swing.JOptionPane;

public class EditLibraryUI extends javax.swing.JFrame {

//Declare array list as public static because it needs to be accessed 
//in other classes
public static ArrayList<VocabWord> LibraryWordsList = 
    new ArrayList<VocabWord>();


int currentRow = 0;

/**
 * Creates new form EditLibraryUI
 */
public EditLibraryUI() {
    initComponents();

    setLabel();


    tableData.setAutoResizeMode(tableData.AUTO_RESIZE_OFF);

    tableData.getColumn("Word").setPreferredWidth(150);
    tableData.getColumn("Definition").setPreferredWidth(300);

}

/**
 * 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.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    chapterLabel = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    tableData = new javax.swing.JTable();
    returnHomeScreenButton = new javax.swing.JButton();
    wordTextField = new javax.swing.JTextField();
    buttonClear = new javax.swing.JButton();
    buttonAdd = new javax.swing.JButton();
    deleteButton = new javax.swing.JButton();
    jScrollPane2 = new javax.swing.JScrollPane();
    definitionTextField = new javax.swing.JTextArea();
    takeTestButton = new javax.swing.JButton();
    editButton = new javax.swing.JButton();
    prepareTableButton = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    chapterLabel.setFont(new java.awt.Font("Segoe Print", 1, 18)); // NOI18N
    chapterLabel.setText("Chapter # Library");

    tableData.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null},
            {null, null}
        },
        new String [] {
            "Word", "Definition"
        }
    ));
    jScrollPane1.setViewportView(tableData);

    returnHomeScreenButton.setText("Return to Home Screen");
    returnHomeScreenButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            returnHomeScreenButtonActionPerformed(evt);
        }
    });

    wordTextField.setText("Word");

    buttonClear.setText("Clear");
    buttonClear.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            buttonClearActionPerformed(evt);
        }
    });

    buttonAdd.setText("Add");
    buttonAdd.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            buttonAddActionPerformed(evt);
        }
    });

    deleteButton.setText("Delete");
    deleteButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            deleteButtonActionPerformed(evt);
        }
    });

    definitionTextField.setColumns(20);
    definitionTextField.setRows(5);
    definitionTextField.setText("Definition\n");
    jScrollPane2.setViewportView(definitionTextField);

    takeTestButton.setText("Take Test");
    takeTestButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            takeTestButtonActionPerformed(evt);
        }
    });

    editButton.setText("Edit");
    editButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            editButtonActionPerformed(evt);
        }
    });

    prepareTableButton.setText("Refresh Table");
    prepareTableButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            prepareTableButtonActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(191, 191, 191)
            .addComponent(chapterLabel)
            .addContainerGap())
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                    .addComponent(wordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 331, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                    .addGap(13, 13, 13)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(returnHomeScreenButton, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(0, 0, Short.MAX_VALUE))
                        .addComponent(jScrollPane1))))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(buttonClear, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(takeTestButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(buttonAdd, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(deleteButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(editButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(prepareTableButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 0, Short.MAX_VALUE))))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(chapterLabel)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(wordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(returnHomeScreenButton))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(18, 18, 18)
                            .addComponent(editButton)
                            .addGap(39, 39, 39)
                            .addComponent(buttonClear)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(prepareTableButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(takeTestButton)
                            .addGap(11, 11, 11))))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(buttonAdd)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(deleteButton)))
            .addContainerGap())
    );

    pack();
}// </editor-fold>                        


public void prepareTable ()
{
    readFromFile();

    for (int i = 0; i <= LibraryWordsList.size() - 1; i++)
    {
       tableData.setValueAt(LibraryWordsList.get(i).getWord(), i, 0);
       tableData.setValueAt(LibraryWordsList.get(i).getDefinition(), i, 1);  
    }

    writeToFile(0);
    currentRow = LibraryWordsList.size();
}

private void returnHomeScreenButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       
    // TODO add your handling code here:

    new HomeScreenUI().setVisible(true);
    this.dispose();

}                                                      

private void buttonClearActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:

    //Clearing all entries in the LibraryWordsList
    //When the clear button is clicked
    LibraryWordsList.clear();

    //Clearing all text entries in dataTable
    for (int i = 0; i <= currentRow; i++) {
       tableData.setValueAt("", i, 0);
       tableData.setValueAt("", i, 1);

    }

    //Reset current entries to 0 
    //So new entries are added to the top of the table
    currentRow = 0;

    clearFields();

    //Clearing entries in the LibraryArrayList 
    //Updates data stored in "LibrarOne" txt file
    writeToFile();
}                                           

private void buttonAddActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:

    //Retrieve text input in the wordTextField and store the 
    //data in String "word"
    String word = wordTextField.getText();

    //Retrieve text input in the definitionTextField and store the 
    //data in String "definition"
    String definition = definitionTextField.getText();

    //Declaring new VocabWord object containing the user defined 
    //Word and definition
    VocabWord newestWord = new VocabWord(word,definition);

    //Add new data to the table so it is visible to the user
    tableData.setValueAt(word, currentRow, 0);
    tableData.setValueAt(definition, currentRow, 1);

    //Add the newly created VocabWord object to the array list 
    //so it can be stored for later use
    LibraryWordsList.add(newestWord);

    //Add one to currentRow so the next word and definition 
    //are added to the next row. 
    currentRow++;

    //Update the data stored in the "LibraryOne" txt file
    writeToFile();
    //Clear the text fields after adding a new word to the data list
    clearFields();

}                                         

public void clearFields()
{
    //Clearing the text fields so the user can enter new data
    definitionTextField.setText("");
    wordTextField.setText(""); 
}


private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
    // TODO add your handling code here:


    int selectedRow = tableData.getSelectedRow();

    tableData.setValueAt("", selectedRow, 0);
    tableData.setValueAt("",selectedRow,1);

    LibraryWordsList.remove(selectedRow);

    currentRow = LibraryWordsList.size();

    writeToFile();

}                                            


private void takeTestButtonActionPerformed(java.awt.event.ActionEvent evt) {                                               
    // TODO add your handling code here:

    new TestScreenUI().setVisible(true);
    this.dispose();

}                                              

private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:

    int selectedRow = tableData.getSelectedRow();

    String newWord = JOptionPane.showInputDialog("Enter new word: ");

    String newDefinition = 
    JOptionPane.showInputDialog("Enter new definition: ");

    LibraryWordsList.get(selectedRow).setWord(newWord);
    LibraryWordsList.get(selectedRow).setDefinition(newDefinition);

    tableData.setValueAt(newWord,selectedRow,0);
    tableData.setValueAt(newDefinition,selectedRow,1);

    writeToFile();


}                                          

private void prepareTableButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                   
    // TODO add your handling code here:

    prepareTable();

}                                                  

public void setLabel () {

    //Accesing classwide variable from createNewLibraryUI.
    chapterLabel.setText(CreateNewLibraryUI.userLibraryName);
}

//write to file method
public static void writeToFile()
{
    //initalize the WriteFile object and let it know 
    //where to write the information
    WriteFile wf = new WriteFile("LibraryOne.txt");

    //data that is written to file
    String outputItem;

    //looping through the array list object and getting the individual
    //object information and write the data to file
    for (int index = 0; index <= LibraryWordsList.size() -1; index++)
    {
        VocabWord nw = LibraryWordsList.get(index);

        //Build the data with comma seperators.
        outputItem = nw.getWord() + "," + 
               nw.getDefinition();

        //Write the data to the file.
        wf.write(outputItem); 
    }

    //Close link to the file.
    wf.close();
}

//Read from file method
private void readFromFile()
{
  //Create link to file on hard drive.
  ReadFile rf = new ReadFile("LibraryOne.txt");

  //Read the first line of data from the data.
  String input = rf.readRecord();

  //Create a while loop to read all the data from the 
  //text file.
  while(input != null)
  {
      //Splits the line of data into a string array so we 
      //can access the individual data.

      String [] data = input.split(",");

      //creat temp area object
      VocabWord newestWord = new VocabWord (data[0],data[1]);

      //add new object ot array list
      LibraryWordsList.add(newestWord);

      //get the next line of data
      input = rf.readRecord();

  }//end of while loop

  //Close link to the file on the hard drive
  rf.close();

}


/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /*
     * Set the Nimbus look and feel
     */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /*
     * If Nimbus (introduced in Java SE 6) is not available, stay with the
     * default look and feel. For details see
     * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(EditLibraryUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(EditLibraryUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(EditLibraryUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(EditLibraryUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /*
     * Create and display the form
     */
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new EditLibraryUI().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JButton buttonAdd;
private javax.swing.JButton buttonClear;
private javax.swing.JLabel chapterLabel;
private javax.swing.JTextArea definitionTextField;
private javax.swing.JButton deleteButton;
private javax.swing.JButton editButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JButton prepareTableButton;
private javax.swing.JButton returnHomeScreenButton;
private javax.swing.JTable tableData;
private javax.swing.JButton takeTestButton;
private javax.swing.JTextField wordTextField;
// End of variables declaration                   
}

0 个答案:

没有答案