Dear all,

I was given a project to write a software that would track contracts. Everything is successful until I read or write the current data from the JTable to the textfile. This also happens when I read the textfile and insert the data into the JTable. The exception I get NullPointerExceltion and happens at around line 68 when saving to txt file and line 101 when reading from txt file. This happens when I click on the 'save' or 'load' button.

Please help. Here is my code that me and another friend have been working on for a few days. Apologies if this is a stupid mistake. I'm new to java.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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;

    public class Main {

    // Set up the size of the GUI window
    private static final int FRAME_WIDTH = 900;
    private static final int FRAME_HEIGHT = 400;
    static JTable contracts;
    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();
        // I need this to be able to put the buttons where I want

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

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

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


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

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

                    BufferedWriter bfw = new BufferedWriter(new FileWriter("Contract_data.txt"));

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

                        for(int j = 0 ; j < contracts.getColumnCount();j++)
            }catch(Exception ex) {

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

        // Method for load button
        buttonLoad.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String line;
                BufferedReader reader;
                        reader = new BufferedReader(new FileReader("Contract_data.txt"));
                        while((line = reader.readLine()) != null) 
                           contracts.add(null, line.split(", ")); 
                    catch(Exception ex){



        // Set up Labels for contracts, description, etc...
        final JLabel lblname = new JLabel("Enter contract name: ");
        lblname.setBounds(20, 5, 150, 100);

        final JLabel lbldesc = new JLabel("Enter description: ");
        lbldesc.setBounds(20, 60, 150, 100);

        final JLabel lbldeadline = new JLabel("Enter deadline: ");
        lbldeadline.setBounds(20, 115, 150, 100);

        final JLabel lblcontact = new JLabel("Enter contact(s):");
        lblcontact.setBounds(20, 170, 150, 100);

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

        final JTextField txtdesc = new JTextField();
        txtdesc.setBounds(180, 95, 100, 25);

        final JTextField txtdeadline = new JTextField();
        txtdeadline.setBounds(180, 150, 100, 25);

        final JTextField txtcontact = new JTextField();
        txtcontact.setBounds(180, 210, 100, 25);

        // Set up of columns in the table
        String[] columns = { "ID", "Contract", "Description", "Deadline", "Contact(s)" };
        // Set up of the table with the appropriate column headers
        final DefaultTableModel model = new DefaultTableModel(null, columns);
        final JTable contracts = new JTable();
        JScrollPane scrollPane = new JScrollPane(contracts);
        scrollPane.setBounds(300, 20, 550, 300);

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

                if (txtdesc.getText().length() == 0) {
                    JOptionPane.showMessageDialog(null, "Error: no contract description");

                // Add an ID number to each entry and add the entry to the table
                model.addRow(new Object[] { String.valueOf(ID),
                        txtname.getText(), txtdesc.getText(),
                        txtdeadline.getText(), txtcontact.getText() });

                // Once entry is added to the table, the text fields are cleared for the next entry

         * 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("Contract Tracker");


Recommended Answers

The common factor on those two lines is the contacts variable
You declare it on line 23, but you never initailse it, so it's null.

And before you refer me to line 153... that creates and initialises a second variable, also called contacts, that is local to the main method, …

Jump to Post

What exactly did you change to fix it. What exactly is the error remaining in load?

Jump to Post

All 7 Replies

Please help! This has been bugging me for a few days. I cannot find any other solution(s)!

The common factor on those two lines is the contacts variable
You declare it on line 23, but you never initailse it, so it's null.

And before you refer me to line 153... that creates and initialises a second variable, also called contacts, that is local to the main method, and goes out of scope before your listeners can be called.

Hi JamesCherrill,

I managed to fix the save button via your comment. But is the 'load' button the same. I can't seem to do anything about that. Same error.

Sorry for my stupidity, I'm trying my best to get the hang of Java.


What exactly did you change to fix it. What exactly is the error remaining in load?

Instead of having static JTable contracts; only on line.23, I changed it to static JTable contracts = new JTable();. Furthermore, I completely removed line 153 as it was causing a heap of troubles. The application is now able to save to the text file.

The problem is reading that text file and adding the read data into the JTable. The problem is, even after your comment, I still get NullPointerException on line.101.

I'm really not sure of how to alter the code to remove that error. Saving the data of JTable works fine but loading it back does not work. The error happens when I click the 'load' button.

Two things stand out...
you write the data with a newline before each field and a tab after each. Presumably that should have been a newline only between complete rows?
JTable does inherit an add method (from JComponent) but I doubt that it's the method you really wanted! Adding a row to the table model (like line 177) would seem more appropriate.

(ps going to bed now - no more from me today)

As @JamesCherrill pointed out, the add method you're using on line 101 is not the correct way to add data to a JTable. You are passing null as a component to public void add(Component comp, Object constraints). If you read the JavaDoc of that method you will find it says the following:

comp - the component to be added
constraints - an object expressing layout contraints for this component
NullPointerException - if comp is null

Hence your NullPointer.

You add data to a table by using its model. More precisely: retrieve the model from the JTable, using its getModel() method. Add your data to the model, using addRow(Object[] objects) for instance. Then assign the model back to the JTable using its setModel(TableModel model) method.

Keep in mind that (as JamesCherrill also pointed out) your datafile currently looks like this:


However, you are splitting on commas in your current code, which will result in this:


I'm assuming this is some sort of homework/practice assignment, so that's up to you to implement correctly (in either the saving, or the loading).

One last remark; if you were to split on commas, what would happen if a user added a comma in his/her input?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.