Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selected cell value in JTable [duplicate]

Tags:

java

swing

jtable

When I double click the cell of the JTable, I want it to take the value of that cell and write it in the textfield. What should I do? Here is what I have tried so far, but I don't know where to go from here:

 table_1.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent me) {
            JTable table = (JTable) me.getSource();
            Point p = me.getPoint();
            int row = table.rowAtPoint(p);
            if (me.getClickCount() == 2) {
                textfield.settext(???????????);
            }
        }
    });  

i understand how it works:

int row = table.rowAtPoint(p);
int column = table.columnAtPoint(p);
textfield.settext(table_1.getValueAt(row, column));
like image 317
amirhtk Avatar asked Jan 08 '23 05:01

amirhtk


2 Answers

Jtable table = (JTable)e.getsource();
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
ObjectType o = (ObjectType)target.getValueAt(row, column) );

Do this. Will get the value in your JTable based on the row and column selected and then casts the returned value to your object type in the table and returns the value at the row, column. This is inside your Listener.

Shown in similar question Possible Dup?

like image 192
Adam Avatar answered Jan 10 '23 19:01

Adam


You can get the value of the table by using:

table.getModel().getValueAt(row, col);

where

  • row - the row whose value is to be queried
  • col - the column whose value is to be queried
  • table - your object name (class jTable)

Note: The column is specified in the table view's display order, and not in the TableModel's column order. This is an important distinction because as the user rearranges the columns in the table, the column at a given index in the view will change. Meanwhile the user's actions never affect the model's column ordering.

In addition, I recommend to read this documentation.

like image 43
Andrew Tobilko Avatar answered Jan 10 '23 19:01

Andrew Tobilko