• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 537
  • Last Modified:

Accessing data of a selected row in a JTable - urgent!

How can I read out the data of a selected row in a JTable?

Usually you want to do something with the data of a selected row. For instance, if you have a table which shows the name of a person, his age, his address and you select say the third entry/row in the table because you want to change the address. How can I do this?
0
dirku
Asked:
dirku
  • 4
1 Solution
 
fontaineCommented:
Get the TableModel used to build up the JTable using JTable.getModel(). The table model
allows you to manipulate the rows and columns of the table. There are methods such as
setValueAt() and getValueAt(). Please refer to the doc of com.sun.java.swing.table.TableModel.java for the full API.

You can identify the row that has been selected via JTable.getSelectedRow(). This returns the index of the last row selected or added to the selection.

Ex:

JTable table = ...
TableModel model = table.getModel();
int row = table.getSelectedRow();
model.setValueAt("Hello!",row,0 /* first column */);

You will maybe have to invalidate()/validate() to see the changes appear on screen.
0
 
fontaineCommented:
To read the content of the first column of the selected row:

String data = (String)model.getValueAt(row,0);
0
 
fontaineCommented:
If you want to use setValueAt(), the cell has to be editable, i.e. the table model isCellEditable()
method has to return true for that particular cell.
0
 
dirkuAuthor Commented:
...and how can I deselect a selected row after clicking on the selected row again (or anywhere else but not on a table's row)?

Will grade you after this answer, okay?
For now I'd give you an A (although I found out what you suggested by myself -> I simply asked to quick. However, good answer.)
0
 
fontaineCommented:
There is a clearSelection() method in JTable that unselects what is currently selected. You
can invoke this method as a menu call-back for example, or in the mouseClicked() method
of a panel implementing the MouseListener interface.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now