Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JTable getting the data of the selected row

Are there any methods that are used to get the data of the selected row? I just want to simply click a specific row with data on it and click a button that will print the data in the Console.

enter image description here

like image 608
ZeroCool Avatar asked Mar 30 '15 12:03

ZeroCool


People also ask

How can I tell if a row is selected in JTable?

So you can call table. getSelectionModel(). isSelectionEmpty() to find out if any row is selected.

How do I sort a row in JTable?

We can sort a JTable in a particular column by using the method setAutoCreateRowSorter() and set to true of JTable class.

How add data from Jtextfield to JTable?

To add the data entered in the JTextFields you will need to register an ActionListener to your add button, in this case jButton1 . To add entries to your table model you could use a mutable model such as DefaultTableModel : DefaultTableModel model = new DefaultTableModel(data, columns);


4 Answers

http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html

You will find these methods in it:

getValueAt(int row, int column)
getSelectedRow()
getSelectedColumn()

Use a mix of these to achieve your result.

like image 86
ManyQuestions Avatar answered Sep 28 '22 06:09

ManyQuestions


You can use the following code to get the value of the first column of the selected row of your table.

int column = 0;
int row = table.getSelectedRow();
String value = table.getModel().getValueAt(row, column).toString();
like image 37
Saminda Peramuna Avatar answered Sep 28 '22 06:09

Saminda Peramuna


if you want to get the data in the entire row, you can use this combination below

tableModel.getDataVector().elementAt(jTable.convertRowIndexToModel(jTable.getSelectedRow()));

Where "tableModel" is the model for the table that can be accessed like so

(DefaultTableModel) jTable.getModel();

this will return the entire row data.

I hope this helps somebody

like image 35
Damilola Fagoyinbo Avatar answered Sep 28 '22 06:09

Damilola Fagoyinbo


Just simple like this:

    tbl.addMouseListener(new MouseListener() {
        @Override
        public void mouseReleased(MouseEvent e) {
        }
        @Override
        public void mousePressed(MouseEvent e) {
            String selectedCellValue = (String) tbl.getValueAt(tbl.getSelectedRow() , tbl.getSelectedColumn());
            System.out.println(selectedCellValue);
        }
        @Override
        public void mouseExited(MouseEvent e) {
        }
        @Override
        public void mouseEntered(MouseEvent e) {
        }
        @Override
        public void mouseClicked(MouseEvent e) {
        }
    });
like image 20
TikTzuki Avatar answered Sep 28 '22 07:09

TikTzuki