Another alternative is to use an event that monitors selections made in the table:
suaTable.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
@Override
public void valueChanged(ListSelectionEvent e) {
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
if(!lsm.isSelectionEmpty()){
//aqui você insere a ação que quer fazer quando
//uma linha for selecionada ou uma seleção for
//alterada na tabela
}
}
}
And do not forget to convert the index from the table to the model, to avoid problems with indexofboundException
if you insert filters into the table.
int rowSel = suaTable.getSelectedRow();//pega o indice da linha na tabela
int indexRowModel = suaTable.getRowSorter().convertRowIndexToModel(rowSel);//converte pro indice do model
If you do not have a method that returns an object of your model, you can use the getValueAt(indexRow, indexColumn)
method to get the values of each column of the line and popularize its object. The method would look more like this:
suaTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
if(!lsm.isSelectionEmpty()){
int rowSel = suaTable.getSelectedRow();//pega o indice da linha na tabela
int indexRowModel = suaTable.getRowSorter().convertRowIndexToModel(rowSel);//converte pro indice do model
//aqui você adapta conforme sua tabela e seu objeto,
//alterando o indice da coluna
seuTable.getModel().getValueAt(indexRowModel, indiceDaColuna);
}
}
});
Another tip would be to use JDialog
for your app's secondary screens, and use JFrame
only on the main, so you can control visibility and easily retrieve information between those windows, even after you have given dispose
to windows. In this link you get information about using JDialogs
, its use is very similar to JFrames
, with the addition of making it a #
Modal window .
In this question has an example similar to yours.
Other references:
Update a Jtable that is in a JFrame from a JDialog
Calling up a JFrame from another JFrame with different classes