Find column # by column name or header - JTable

java, jtable, swing, tablecolumn

Solution

I accomplished my task using the ternary operator in my code

 int colNo = ((tbl.getModel().getColumnName(tcl.getColumn()).equalsIgnoreCase("Qty"))
||  (tbl.getModel().getColumnName(tcl.getColumn()).equalsIgnoreCase("Weight"))
|| (tbl.getModel().getColumnName(tcl.getColumn()).equalsIgnoreCase("Wt"))
 ? tcl.getColumn() : -1);

The full code of my general Table Cell Listener using Bob Camick's Table Cell Editor)!

final JTable table = (JTable) jComp.get(a);
tbl.getTableHeader().setReorderingAllowed(false); 

 Action actionProd = new AbstractAction() {

    public void actionPerformed(ActionEvent e) {

        Utility util = new Utility("GoldNew");

        TableCellListener tcl = (TableCellListener) e.getSource();
        System.out.println("Row   : " + tcl.getRow());
        System.out.println("Column: " + tcl.getColumn());
        System.out.println("Old   : " + tcl.getOldValue());
        System.out.println("New   : " + tcl.getNewValue());
        int colNo = ((table.getModel().getColumnName(tcl.getColumn()).equalsIgnoreCase("Qty"))
                || (table.getModel().getColumnName(tcl.getColumn()).equalsIgnoreCase("Weight"))
                || (table.getModel().getColumnName(tcl.getColumn()).equalsIgnoreCase("Wt"))
                ? tcl.getColumn() : -1);

        if (tcl.getColumn() == colNo) {
            int wt = 0;
            Object qtyO = tcl.getNewValue();
            try {
                qtyO = tcl.getNewValue();
                if (qtyO != null) {
                    wt = Integer.parseInt(qtyO.toString());
                }

                if (wt < 0) {
                    table.getModel().setValueAt(tcl.getOldValue(), tcl.getRow(), colNo);
                }

            } catch (Exception ex) {
                util.ShowMessage("Please enter the Numbers only", "Error!");
                table.getModel().setValueAt(tcl.getOldValue(), tcl.getRow(), colNo);
                ex.printStackTrace();
            }




        }

    }
};
TableCellListener tclProd = new TableCellListener(table, actionProd);       

Problem

I want to implement a general validation class for my jtables in different forms to check the qty column , as the qty column No in different tables of different forms is different. For this i want to get the column value by column Name similarly in C# or VB. My requirement is as follows. ``` int qty=jtable.getValueAt(rowNo,"columnName"); ``` Now i am using ``` int qty=jtable.getValueAt(rowNo,colNo); ``` Is there any way to find column # by column Name or Header Of JTable?

Original source