7

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

5 Answers5

11

You should try using this:

int qty = jtable.getValueAt( rowNo, jtable.getColumn("columnName").getModelIndex() );
Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
Ankur
  • 1,268
  • 18
  • 22
6

You should probably be asking the TableModel, rather than the JTable, which may have its columns rearranged. One approach would be to let your TableModel implement a suitable interface, for example,

public interface Quantifiable {
    public int getQuantity(int row);
}

Addendum: Please tell how to implement this interface.

Much depends on the relationship among your existing TableModel classes. Lets say the all have a numeric quantity in some column. If quantityCol is the model index a column having the type Number, you could do something like this:

public class QuantifiableTableModel
        extends AbstractTableModel implements Quantifiable {

    private int quantityCol;

    public QuantifiableTableModel(int quantityCol) {
        this.quantityCol = quantityCol;
    }

    @Override
    public int getQuantity(int row) {
        Number n = (Number) getValueAt(row, quantityCol);
        return n.intValue();
    }
    ...
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • please tell how to implement this interface – Syed Muhammad Mubashir Nov 20 '12 at 04:28
  • sorry my requirement is simply jtable.getValueAt(rowNo,"columnName") as in your question you have given constructor of the class QuantifiableTableModel(int quantityCol) but i don't know the column number.In question i only mention the validation as the use case of the problem and not the problem it self. I thought you don't understand my problem. @trashgod – Syed Muhammad Mubashir Nov 20 '12 at 06:48
  • Also consider implementing `Iterable`, which "allows an object to be the target of the "foreach" statement." – trashgod Nov 20 '12 at 14:40
2

I was facing the same issue. This was my implementation:

int nameColNo = getColumnIndex(table, "Name");
String name = (String)table.getValueAt(rowNo, nameColNo);

private int getColumnIndex (JTable table, String header) {
    for (int i=0; i < table.getColumnCount(); i++) {
        if (table.getColumnName(i).equals(header)) return i;
    }
    return -1;
}

Of course, if it was you who created the table headers its expected to never return -1, else you might treat it accordingly.

muriloap
  • 21
  • 1
2

Hi this is a simple answer to Your the question:

int qty=jtable.getValueAt(rowNo,jtable.convertColumnIndexToView(jtable.getColumn("columnName").getModelIndex()));
1

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);       
  • Brr, this is an ugly solution. At least use a regular loop to loop over the columns. The `JTable` provide all this information. But better to follow @trashgod 's approach of querying the model. And when the column or row order in your `JTable` is different from the ones in your model (which is standard functionality of the `JTable`) your code will not work as expected – Robin Nov 20 '12 at 09:02
  • Actually the name is **Rob Camickr** and not ***Bob Camickr*** :-) By the way **""What's in the name""**, as said by Shakespeare, quoting his name. – nIcE cOw Nov 20 '12 at 09:47
  • @Robin I have tested my solution it's working for me as i am mostly playing with table model in my application. – Syed Muhammad Mubashir Nov 20 '12 at 11:19