Search code examples
javaswingjtableverify

How to Verify Required Fields in JTable


I have a JTable and I need to verify the input of 2 columns. That is 2 specific columns need to contain proper values in every cell. If they do then I want to enable a button. I know how to enable a button but I don't know where/how to verify those 2 columns. What table model method would be the appropriate place to verify those cells and enable the button, if any? I'm thinking I need a listener for those cells and process them in loseFocus(). The only issue is if the user leaves the cursor in one of those cells so it never loses focus even though the entry is valid. This must be a relatively common practice so there must be a best programming practice to accomplish it. TIA.


Solution

  • A TableModelListener added to the table's model will notify you of any change in the model's data. Within the listener, you can iterate through the rows, extracting column data with getValueAt(...) method, and then enable/disable your JButton or its Action accordingly.

    For example, in the following code there are two columns of integers. The ints in the B column must be greater than the A column for the data to be valid. If this is not the case (or if any value is null), the button is disabled:

    import java.awt.BorderLayout;
    
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableModel;
    
    public class TableFun extends JPanel {
        private Integer[][] DATA = {{1, 2}, {3, 4}, {5, 6}};
        private String[] COL_NAMES  = {"A", "B"};
        private DefaultTableModel model = new DefaultTableModel(DATA, COL_NAMES) {
            public java.lang.Class<?> getColumnClass(int columnIndex) {
                return Integer.class;
            };
        };
        private JTable table = new JTable(model);
        private JButton myButton = new JButton("My Button");
    
        public TableFun() {
            model.addTableModelListener(new TableModelListener() {
    
                @Override
                public void tableChanged(TableModelEvent e) {
                    boolean valid = true;
                    for (int row = 0; row < model.getRowCount(); row++) {
                        Integer valueA = (Integer) model.getValueAt(row, 0);
                        Integer valueB = (Integer) model.getValueAt(row, 1);
    
                        if (valueA == null || valueB == null || valueA.compareTo(valueB) > 0) {
                            valid = false;
                        }
                    }
                    myButton.setEnabled(valid);
                }
            });
    
            JPanel panel = new JPanel();
            panel.add(myButton);
    
            setLayout(new BorderLayout());
            add(new JScrollPane(table));
            add(panel, BorderLayout.PAGE_END);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> createAndShowGui());
        }
    
        private static void createAndShowGui() {
            TableFun mainPanel = new TableFun();
            JFrame frame = new JFrame("TableFun");
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.add(mainPanel);
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    }