-4

I have to create a GUI which uses a table that takes data from an XML and then is able to sort the colums by clicking them ... so far so good except for the sorting part which gives me an NullPointerException (my favorite) and I can't figure it out since everything worked out fine until I put this line of code in table.setAutoCreateRowSorter(true);

Any ideas as to why it doesn't work?

JTable table;

public Table() {
    ArrayList<Person> personList = XML.getPersonList();
    JPanel mainPanel = new JPanel();
    JPanel upperPanel = new JPanel();
    JPanel lowerPanel = new JPanel();
    JButton createPersonButton = new JButton("Create");
    String[] collumnNames = { "Name", "Age", "Email" };
    String[][] data;
    data = new String[50][3];
    createPersonButton.addActionListener(new createListener());
    setLayout(new GridLayout(1, 2));

    for (int i = 0; i < personList.size(); i++) {
        data[i][0] = personList.get(i).getEmail();
        data[i][1] = personList.get(i).getFullName();
        data[i][2] = personList.get(i).getAge();

    }
    table.setAutoCreateRowSorter(true);

    table = new JTable(data, collumnNames);
    table.setPreferredScrollableViewportSize(new Dimension(430, 300));
    table.setFillsViewportHeight(true);
    JScrollPane scroll = new JScrollPane(table);
    table.setFillsViewportHeight(true);
    lowerPanel.add(createPersonButton);
    upperPanel.add(scroll);
    mainPanel.add(upperPanel);
    mainPanel.add(lowerPanel);
    setContentPane(mainPanel);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(650, 400);
    setVisible(true);

}

}

Andrew Thompson
  • 166,747
  • 40
  • 210
  • 420
Java Pleb
  • 19
  • 4
  • 1
    1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) See [Detection/fix for the hanging close bracket of a code block](http://meta.stackexchange.com/q/251795/155831) for a problem I could no longer be bothered fixing. *"..takes data from an XML.."* Obviosly, hard code some data for the table. – Andrew Thompson May 01 '16 at 14:20
  • 2
    3) Always copy/paste error and exception output! 4) See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556) – Andrew Thompson May 01 '16 at 14:21

1 Answers1

1
table.setAutoCreateRowSorter(true);
table = new JTable(data, collumnNames);

Looks to me like you are trying to set the sorter before you even create an instance of the table.

The code order should be:

table = new JTable(data, collumnNames);
table.setAutoCreateRowSorter(true);    
camickr
  • 316,400
  • 19
  • 155
  • 279