Search code examples
javaswingjtablerowfilter

Create a way to stop to many duplicate values coming up in a JTable


I have the following code for a JTable.

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.lang.*;
import java.awt.event.*;
///////////
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
import javax.swing.text.Document;
import javax.swing.table.TableRowSorter;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
///////////
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.table.*;

public class SelectTeam
{
    JFrame myMainWindow = new JFrame("Select Team");
    
    JPanel  firstPanel = new JPanel(); //a panel for first tab

    //first panel components
    JScrollPane myScrollTable;
    JTextField filterAthID;
    JTextField filterForeName;
    TableRowSorter sorter;
    DefaultTableModel model;
    JLabel AthleteID = new JLabel();
    JLabel ForeName = new JLabel();
    JTable athTable;
    JComboBox bPartInEventCB;
    int nextPosition=0;
    
    public void runGUI()
    {       
        myMainWindow.setBounds(10, 10, 1296, 756); //set position, then dimensions
        myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        myMainWindow.setLayout(new GridLayout(1,1));
        
        createFirstPanel(); //call method to create each panel
        
        myMainWindow.getContentPane().add(firstPanel); //adds the tabbedpane to mainWindow
        
        myMainWindow.setVisible(true); //make the GUI appear
        myMainWindow.setResizable(false);
    }
    
    public void createFirstPanel()
    {
        firstPanel.setLayout(null);
        
        AthleteID.setLocation(200,120); //Sets the location
        AthleteID.setSize(150,26); //Sets the size
        AthleteID.setText("Athlete ID Search:");
        firstPanel.add(AthleteID); //Adds it to the panel
        
        ForeName.setLocation(731,120); //Sets the location
        ForeName.setSize(150,26); //Sets the size
        ForeName.setText("Athlete Name Search:");
        firstPanel.add(ForeName); //Adds it to the panel
        
        String[] aHeaders = {"Athlete ID","Forename","Surname","On The Team"};
        String[][] sampleData = new String[10][4];
        
        sampleData[0][0]= "JS98";
        sampleData[0][1]= "John";
        sampleData[0][2]= "Smith";
        sampleData[0][3]= "Yes";
        
        sampleData[1][0]= "DB83";
        sampleData[1][2]= "David";
        sampleData[1][2]= "Bowser";
        sampleData[1][3]= "No";
        
        sampleData[2][0]= "TR68";
        sampleData[2][3]= "Trevor";
        sampleData[2][2]= "Radner";
        sampleData[2][3]= "No";
        
        sampleData[3][0]= "JR97";
        sampleData[3][4]= "Jon";
        sampleData[3][2]= "Raynor";
        sampleData[3][3]= "Yes";
        
        sampleData[4][0]= "AF11";
        sampleData[4][5]= "Adam";
        sampleData[4][2]= "Fawcett";
        sampleData[4][3]= "Yes";
        
        sampleData[5][0]= "ES96";
        sampleData[5][6]= "Emma";
        sampleData[5][2]= "Spender";
        sampleData[5][3]= "Yes";
        
        sampleData[6][0]= "GF56";
        sampleData[6][7]= "Gerald";
        sampleData[6][2]= "Fits";
        sampleData[6][3]= "No";
        
        sampleData[7][0]= "NC70";
        sampleData[7][8]= "Nicola";
        sampleData[7][2]= "Condron";
        sampleData[7][3]= "Yes";
        
        sampleData[8][0]= "SI25";
        sampleData[8][9]= "Sir";
        sampleData[8][2]= "Ivan";
        sampleData[8][3]= "Yes";
        
        sampleData[9][0]= "LH56";
        sampleData[9][10]= "Lord";
        sampleData[9][2]= "Hammerlock";
        sampleData[9][3]= "Yes";
        
        model = new DefaultTableModel(sampleData,aHeaders)
        {
            @Override
            public boolean isCellEditable(int row, int column) 
            {
                if (column < 3) 
                {
                    return false;
                } 
                
                else 
                {
                    return true;
                }
            }
        };
        athTable = new JTable(model);
        athTable.setAutoCreateRowSorter(true);
        athTable.setRowHeight(20);
        
        myScrollTable = new JScrollPane(athTable); 
        myScrollTable.setSize(1082,600); 
        myScrollTable.setLocation(200,145); 
        System.out.println("Creating compare table");
        
        TableColumn sportColumn = athTable.getColumnModel().getColumn(3);
        bPartInEventCB = new JComboBox();
        bPartInEventCB.addItem("Yes");
        bPartInEventCB.addItem("No");
        sportColumn.setCellEditor(new DefaultCellEditor(bPartInEventCB));
        
        sorter = new TableRowSorter(athTable.getModel());
        List sortKeys = new ArrayList();
        sortKeys.add(new RowSorter.SortKey(3, SortOrder.DESCENDING));
        sorter.setSortKeys(sortKeys);
        athTable.setRowSorter(sorter);
        
        filterAthID = new JTextField(10);
        filterAthID.setSize(425,26); 
        filterAthID.setLocation(306,120);
        filterAthID.setToolTipText("Enter Athlete ID");
        firstPanel.add(filterAthID);
        
        filterForeName = new JTextField(10);
        filterForeName.setSize(425,26); 
        filterForeName.setLocation(857,120);
        filterForeName.setToolTipText("Enter Athlete Name");
        firstPanel.add(filterForeName);
        
        Document doc = filterAthID.getDocument();
        DocumentListener listener = new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) 
            {
                newFilter();
            }

            @Override
            public void removeUpdate(DocumentEvent e) 
            {
                newFilter();
            }

            @Override
            public void changedUpdate(DocumentEvent e) 
            {
                newFilter();
            }
        };
        doc.addDocumentListener(listener);
    
        Document docb = filterForeName.getDocument();
        DocumentListener listenerb = new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) 
            {
                newFilter();
            }

            @Override
            public void removeUpdate(DocumentEvent e) 
            {
                newFilter();
            }

            @Override
            public void changedUpdate(DocumentEvent e) 
            {
                newFilter();
            }
        };
        docb.addDocumentListener(listenerb);
        
        for(int i=0;i<nextPosition;i++)
        {
            System.out.println(athTable.getModel().getValueAt(i,0));
        }
        
        firstPanel.add(myScrollTable);
    }
    
    private void newFilter()
    {
        RowFilter rf = null;
        try 
        {
            List<RowFilter<Object,Object>> filters = new ArrayList<RowFilter<Object,Object>>(2);
            filters.add(RowFilter.regexFilter("(?i)"+filterAthID.getText(), 0));
            filters.add(RowFilter.regexFilter("(?i)"+filterForeName.getText(), 1));
            rf = RowFilter.andFilter(filters);
            
            List<RowFilter<Object,Object>> filtersb = new ArrayList<RowFilter<Object,Object>>(2);
            filtersb.add(RowFilter.regexFilter("(?i)"+filterForeName.getText(), 1));
            filtersb.add(RowFilter.regexFilter("(?i)"+filterForeName.getText(), 2));
            rf = RowFilter.orFilter(filtersb);
        } 
        catch (java.util.regex.PatternSyntaxException e) 
        {
            return;
        }
        sorter.setRowFilter(rf);
    }
    
    public static void main(String[] args)
    {
        SelectTeam st = new SelectTeam();
        st.runGUI();
    }
}

It creates a table which looks like this.

Table looks like this

I would like to be able make it so if there are more than 8 values of "Yes" in the last column a popup comes up JOptionPane.showMessageDialog(null, "Please remove a athlete from the team"); My only problem is I am unable to do this since I don't know how. I would appreciate any help in doing this.

Thanks

Edit

So I have added the following code

JButton btnUpdate = new JButton();

btnUpdate.setLocation(0,120);
btnUpdate.setSize(200,50);
btnUpdate.setText("Update the team");
btnUpdate.addActionListener(this);
firstPanel.add(btnUpdate);

public void checkCount(TableModel model) 
    {
        int count=0;
        for (int row=0; row<model.getRowCount(); row++) 
        {
            if ("Yes".equals(model.getValueAt(row, 3)))
            {
            count++;
            }
        }
      
        if (count>8)
        {
            JOptionPane.showMessageDialog(null, "Please remove a athlete from the team");
        }
    }
    
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource() == btnUpdate)
        {
            checkCount();
        }
    }

However when I compile this i get this error

Error

So what argument would I pass to make this work?


Solution

  • Go through the TableModel counting the yes value from the last column. After that compare the counter with 8 and show the message if necessary.

    Like this (is not tested)

    public void checkCount(TableModel model) {
      int count=0;
      for (int row=0; row<model.getRowCount(); row++) {
        if ("Yes".equals(model.getValueAt(row, 3)) {
            count++;
        }
      }
      if (count>8) {
        JOptionPane.showMessageDialog(null, "Please remove a athlete from the team");
      }
    }