javaswingarraylistjtabledefaulttablemodel

Searching ArrayList using JTable and JButton


I have an ArrayList holding football matches and when the user types a date and presses "search" button, a new JTable opens showing you all matches played on that day. I have looped to get the date and compared it to the input inside the JTextField but it just gives me an empty table even if there is a record of a match played on the date the user enters. In this code below, I am just using hitting enter on JTextField to execute search because I do not know how to map JTextField to JButton. I have tried but it just prints the search Jbutton name.

 public void searchMatch(ArrayList<Matches> searchMatch, String e)
{
    DefaultTableModel searchModel = new DefaultTableModel();
    for(int i = 0; i < searchMatch.size(); i++)
    {
        if(searchMatch.get(i).getM_date().equals(e))
        {
            System.out.println(searchMatch.get(i).getM_date());
            String date = searchMatch.get(i).getM_date();
            String teamName = searchMatch.get(i).getM_teamName();
            String teamName2 = searchMatch.get(i).getM_teamName2();
            int goalsScoredTeam1 = searchMatch.get(i).getGoalsTeam1();
            int goalsScoredTeam2 = searchMatch.get(i).getGoalsTeam2();

            Object[] row = {teamName, teamName2, goalsScoredTeam1, goalsScoredTeam2,date};
            searchModel.addRow(row);

            JTable searchTable = new JTable(searchModel);
            searchTable.setFillsViewportHeight(true);
            JPanel searchPanel = new JPanel();
            JScrollPane scrollPane = new JScrollPane(searchTable);
            searchPanel.add(scrollPane);

            JFrame frame = new JFrame("Searched Matches");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            searchTable.setOpaque(true);
            frame.setContentPane(searchPanel);

            frame.pack();
            frame.setSize(500, 500);
            frame.setVisible(true);
        }
    }

}

Solution

  • DefaultTableModel searchModel = new DefaultTableModel();
    

    You TableModel has no columns to display.

    Even though you add rows of data, none of the data can be displayed unless you also have defined the "column names" for the TableModel.

    Your code should be something like:

    String columnNames = { "Date", "Name", "..." };
    DefaultTableModel searchModel = new DefaultTableModel(columnNames, 0);
    

    Which will create an empty TableModel with just the column names. Your looping code will then add each row of data.

    Note, you should also look at storing all the data in your TableModel and then just filter the TableModel. Read the section from the Swing tutorial on Sorting and Filtering for a working example.