Java JTable getting the data of the selected row

2020-07-02 10:02发布

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

4条回答
Juvenile、少年°
2楼-- · 2020-07-02 10:29

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

tableModel.getDataVector().elementAt(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

查看更多
家丑人穷心不美
3楼-- · 2020-07-02 10:31

using from ListSelectionModel:

ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
  public void valueChanged(ListSelectionEvent e) {
    String selectedData = null;

    int[] selectedRow = table.getSelectedRows();
    int[] selectedColumns = table.getSelectedColumns();

    for (int i = 0; i < selectedRow.length; i++) {
      for (int j = 0; j < selectedColumns.length; j++) {
        selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
      }
    }
    System.out.println("Selected: " + selectedData);
  }

});

see here.

查看更多
老娘就宠你
4楼-- · 2020-07-02 10:39

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();
查看更多
萌系小妹纸
5楼-- · 2020-07-02 10:49

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.

查看更多
登录 后发表回答