2013-10-13 4 views
0

Я чувствую, что я близок, но все еще сталкиваюсь с ошибками, которые я не понимаю. Я пытаюсь записать данные из моего JTable в текстовый файл, используя кнопку сохранения. Мне также нужно загрузить из файла обратно в JTable. Любые предложения, почему это работает неправильно.Запись текстового файла из JTable и чтение из текстового файла в JTable

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.FileWriter; 
import java.io.FileReader; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.JScrollPane; 
import javax.swing.JTable; 
import javax.swing.JTextField; 
import javax.swing.table.DefaultTableModel; 


/*PayrollProgram.java 
* Created by: Steve Totten 
* Created on: 10-13-2013 
* This program allows the user to enter the contact's 
* name, Email address, age, and phone number. Then the program 
* adds the information to a table for easy viewing 
* The program has a save button to save to a data file 
* it also has a load button that will read from a file to the table 
*/ 

    public class ContactInfo { 

    // Set up the size of the GUI window 
    private static final int FRAME_WIDTH = 900; 
    private static final int FRAME_HEIGHT = 400; 
    static JTable tblContacts; 
    static int ID = 0; 

    public static void main(String[] args) { 

     // Set up the user interface 
     final JFrame frame = new JFrame(); 
     final JPanel buttonPanel = new JPanel(); 
     frame.add(buttonPanel); 
     // I need this to be able to put the buttons where I want 
     buttonPanel.setLayout(null); 

     // Set up Add button and its location 
     final JButton buttonAdd = new JButton(" Add "); 
     buttonAdd.setBounds(50, 325, 100, 20); 
     buttonPanel.add(buttonAdd); 


     // Set up Exit button and its location 
     final JButton buttonExit = new JButton("Exit"); 
     buttonExit.setBounds(200, 325, 100, 20); 
     buttonPanel.add(buttonExit); 

     // Method for exit button 
     buttonExit.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 

       System.exit(0); 
      } 
     }); 

     // Set up Save button and its location 
     final JButton buttonSave = new JButton("Save"); 
     buttonSave.setBounds(350, 325, 100, 20); 
     buttonPanel.add(buttonSave); 

     // Set up Save button method 
     buttonSave.addActionListener(new ActionListener(){ 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       try{ 

        BufferedWriter bfw = new BufferedWriter(new FileWriter("C:\\Users\\Steve\\Workspace\\ContactInfo\\ContactInfo.txt")); 

         for (int i = 0 ; i < tblContacts.getRowCount(); i++) 
         { 

         for(int j = 0 ; j < tblContacts.getColumnCount();j++) 
         { 
          bfw.newLine(); 
          bfw.write((String)(tblContacts.getValueAt(i,j))); 
          bfw.write("\t");; 
         } 
         } 
         bfw.close(); 
      }catch(Exception ex) { 

       ex.printStackTrace(); 
      } 
      } 
     }); 
     // Set up Load button and its location 
     final JButton buttonLoad = new JButton("Load"); 
     buttonLoad.setBounds(500, 325, 100, 20); 
     buttonPanel.add(buttonLoad); 

     // Method for load button 
     buttonLoad.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       String line; 
       BufferedReader reader; 
        try{  
         reader = new BufferedReader(new FileReader("C:\\Users\\Steve\\Workspace\\ContactInfo\\ContactInfo.txt")); 
         while((line = reader.readLine()) != null) 
         { 
          tblContacts.add(null, line.split(", ")); 
         } 
         reader.close(); 
        } 
        catch(Exception ex){ 

       ex.printStackTrace(); 

        } 

      } 
     }); 
     // Set up Labels for name, hours, and pay rate 
     final JLabel lblFirst = new JLabel("Enter First Name: "); 
     lblFirst.setBounds(20, 5, 150, 100); 
     buttonPanel.add(lblFirst); 

     final JLabel lblLast = new JLabel("Enter Last Name: "); 
     lblLast.setBounds(20, 60, 150, 100); 
     buttonPanel.add(lblLast); 

     final JLabel lblAddress = new JLabel("Enter their Age: "); 
     lblAddress.setBounds(20, 115, 150, 100); 
     buttonPanel.add(lblAddress); 

     final JLabel lblAge = new JLabel("Enter Email Address:"); 
     lblAge.setBounds(20, 170, 150, 100); 
     buttonPanel.add(lblAge); 

     final JLabel lblPhone = new JLabel("Enter phone number:"); 
     lblPhone.setBounds(20, 225, 150, 100); 
     buttonPanel.add(lblPhone); 


     // Set up textboxes for all expected inputs 
     final JTextField txtFirst = new JTextField(); 
     txtFirst.setBounds(180, 40, 100, 25); 
     buttonPanel.add(txtFirst); 

     final JTextField txtLast = new JTextField(); 
     txtLast.setBounds(180, 95, 100, 25); 
     buttonPanel.add(txtLast); 

     final JTextField txtAge = new JTextField(); 
     txtAge.setBounds(180, 150, 100, 25); 
     buttonPanel.add(txtAge); 

     final JTextField txtPhone = new JTextField(); 
     txtPhone.setBounds(180, 260, 100, 25); 
     buttonPanel.add(txtPhone); 

     final JTextField txtEmail = new JTextField(); 
     txtEmail.setBounds(180, 210, 100, 25); 
     buttonPanel.add(txtEmail); 

     // Set up of columns in the table 
     String[] columns = { "ID", "Last Name", "First Name", "Age", "Email Address", 
       "Phone Number" }; 
     // Set up of the table with the appropriate column headers 
     final DefaultTableModel model = new DefaultTableModel(null, columns); 
     final JTable tblContacts = new JTable(); 
     tblContacts.setModel(model); 
     JScrollPane scrollPane = new JScrollPane(tblContacts); 
     scrollPane.setBounds(300, 20, 550, 300); 
     buttonPanel.add(scrollPane); 


     // Save button methods, including validation checking 
     buttonAdd.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       if (txtFirst.getText().length() == 0) { 
        JOptionPane.showMessageDialog(null, "Error: no first name"); 
        return; 
       } 

       if (txtLast.getText().length() == 0) { 
        JOptionPane.showMessageDialog(null, "Error: no last name"); 
        return; 
       } 

       int age = 0; 
       try { 
        age = Integer.parseInt(txtAge.getText()); 
       } catch (Exception ex) { 
        JOptionPane.showMessageDialog(null, 
          "Error: invalid age value"); 
        return; 
       } 

       if (age < 0 || age > 120) { 
        JOptionPane.showMessageDialog(null, 
          "Error: invalid age range (0 - 120 allowed)"); 
        return; 
       } 

       if (txtPhone.getText().length()==0){ 
        JOptionPane.showMessageDialog(null, "Error: no phone number "); 
        return; 
       } 


       // Add an ID number to each entry and add the entry to the table 
       ID++; 
       model.addRow(new Object[] { String.valueOf(ID), 
         txtLast.getText(), txtFirst.getText(), 
         txtAge.getText(), txtEmail.getText(), txtPhone.getText() }); 


       // Once entry is added to the table, the text fields are cleared for the next entry 
       txtLast.setText(""); 
       txtFirst.setText(""); 
       txtAge.setText(""); 
       txtPhone.setText(""); 
       txtEmail.setText(""); 



      } 
     });  
     /* 
     * This sets the size of the window along with the title and it sets up 
     * the exit on close X button to close the window when the X is clicked. 
     */ 

     frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); 
     frame.setTitle("Contact Information"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
    } 

} 
+1

'' ... но все еще запутываются в ошибки, которые я не понимаю. "' - пожалуйста, поделитесь с нами полными сообщениями об ошибках/исключениях. Также укажите номера строк, связанные с ошибками. –

ответ

2

Выводы и предложения:

  • Вы получаете NullPointException (NPE) при попытке использовать JTable.
  • Это потому, что вы затеняете поле класса, tblContacts. Это означает, что вы объявляете это поле в классе, а затем повторно объявите и инициализируйте его в основном методе. Ну, когда вы повторно объявляете переменную, это новая и отдельная переменная, поэтому вы оставляете поле класса null.
  • Решение состоит в том, чтобы не повторно объявлять переменную где-либо еще.
  • Также, надеюсь, этот код является всего лишь демонстрационным кодом, а не вашей реальной программой. В вашей реальной программе у вас не было бы никакого этого кода в статическом основном методе (или любом статическом методе, но не очень кратком главном методе), и большинство ваших полей будут нестатистическими полями экземпляра.

Пример затенения:

public class Foo { 
    private int bar; // class field 

    public Foo() { 
    int bar = 3; // I've re-declared bar here and so the class field is still unassigned. 
    } 
} 

Чтобы исправить это:

public class Foo { 
    private int bar; // class field 

    public Foo() { 
    bar = 3; // bar not re-declared 
    } 
} 

разницу?

+0

Это помогает, спасибо! – user2876507

+0

@ пользователь2876507: добро пожаловать. Конечно, вы обнаружите больше проблем, как только исправите их, но постарайтесь по-иному исправить ваш NPE - изучите строку, которая генерирует исключение, а затем оглянитесь назад, чтобы понять, почему переменные не были инициализированы. –

Смежные вопросы