问题
I have a problem with the selection of rows on my JTable instances.
This is what I would like to to:
I want to have two equal tables with the same data in the rows. When you select a row on the first table, e g the third row, I also want the third row on the second table to be selected automatically. I have solved this by adding a ListSelectionListener
to the JTable that updates a class that just hold the selected value. Then that class triggers the other JTable with the selected value from the first.
What my problem is:
My problem occurs when the user sorts the rows on one of the tables. Then the view changes, but not the underlying objects in the model, that has the same order as before.
Let´s say the tables looks like this when I start the application:
Column_1_header_in_table_1 Column_1_header_in_table_2
Peter Peter
John John
Steve Steve
When selecting the first row in table 1
(which is Peter), then the row containing Peter shall be selected on table 2
which is also the first row.
But if I press the column header on table 1
so the column is sorted, then the view of that table changes to this:
Column_1_header_in_table_1 Column_1_header_in_table_2
John Peter
Steve John
Peter Steve
Now, if I select the first row in table 1
(that is John), the first row in table 2
will be selected (that is Peter). But I want the row with the same name as in table 1
to be selected on table 2
, which is row 2 on table 2
.
Is there some approach I can use to tackle this problem?
EDIT
Ok, I will try to describe my solution with the below code that I have written without an editor, so I may contain some errors. But I just want to show conceptually how it works right now.
First I have done this interface that the MyTable implements:
public interface TableUpdater {
public void updateTable(int age);
}
The PersonHolder class just holds the last selected value and triggers the other table when a new value is selected from the first.
public class PersonHolder {
private static int age;
private List<TableUpdater> tables = new ArrayList<>();
public static void subscribe(TableUpdater table){
tables.add(table);
}
public static void setValue(int value){
age = value;
for(TableUpdater table : tables) {
table.updateTable(age);
}
}
public static int getValue(){
return age;
}
}
Then we have the Table itself:
public class MyTable extends JTable implements TableUpdater {
public MyTable {
table.getSelectionModel().addListSelectionListener(new MySelectionListener());
PersonHolder.subscribe(this);
}
...
@Override
public void updateTable(int age) {
this.getSelectionModel().setSelectionInterval(age, age);
}
private class MySelectionListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
Person p = (Person)getValueAt(e.getLastIndex(), 0);
PersonHolder.setValue(p.getAge());
}
}
}
回答1:
You should use: javax.swing.JTable.convertRowIndexToModel(int)
to convert the current selection index to a model index value and then, in the other table, convert the model index back to a view index with javax.swing.JTable.convertRowIndexToView(int)
and set that index as the selected row (this assuming that the model in both tables is the same or is equivalent, otherwise you will have to make a look-up based on values).
Here is an example of what I have in mind (I even shuffled the baseModel of both JTable's and perform an index lookup in the other one):
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
public class TestSortedTable {
class MyTableModel extends AbstractTableModel {
private List<Person> baseModel;
public MyTableModel(List<Person> baseModel) {
super();
this.baseModel = new ArrayList<Person>(baseModel);
}
@Override
public int getRowCount() {
return baseModel.size();
}
@Override
public String getColumnName(int column) {
switch (column) {
case 0:
return "First Name";
case 1:
return "Last Name";
}
return null;
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
return getPersonAtIndex(rowIndex).getFirstName();
case 1:
return getPersonAtIndex(rowIndex).getLastName();
}
return null;
}
public Person getPersonAtIndex(int rowIndex) {
return baseModel.get(rowIndex);
}
public int getIndexOfPerson(Person person) {
return baseModel.indexOf(person);
}
}
protected void initUI() {
List<Person> personModel = new ArrayList<TestSortedTable.Person>();
personModel.add(new Person("John", "Smith"));
personModel.add(new Person("Peter", "Donoghan"));
personModel.add(new Person("Amy", "Peterson"));
personModel.add(new Person("David", "Anderson"));
JFrame frame = new JFrame(TestSortedTable.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Collections.shuffle(personModel);
final MyTableModel table1Model = new MyTableModel(personModel);
final JTable table1 = new JTable(table1Model);
table1.setAutoCreateRowSorter(true);
Collections.shuffle(personModel);
final MyTableModel table2Model = new MyTableModel(personModel);
final JTable table2 = new JTable(table2Model);
table2.setAutoCreateRowSorter(true);
table1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
int index = table1.getSelectedRow();
if (index > -1) {
int table1ModelIndex = table1.convertRowIndexToModel(table1.getSelectedRow());
Person p = table1Model.getPersonAtIndex(table1ModelIndex);
int table2ModelIndex = table2Model.getIndexOfPerson(p);
int indexInTable2 = table2.convertRowIndexToView(table2ModelIndex);
table2.getSelectionModel().setSelectionInterval(indexInTable2, indexInTable2);
}
}
});
table2.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
int index = table2.getSelectedRow();
if (index > -1) {
int table2ModelIndex = table2.convertRowIndexToModel(table2.getSelectedRow());
Person p = table2Model.getPersonAtIndex(table2ModelIndex);
int table1ModelIndex = table1Model.getIndexOfPerson(p);
int indexInTable1 = table1.convertRowIndexToView(table1ModelIndex);
table1.getSelectionModel().setSelectionInterval(indexInTable1, indexInTable1);
}
}
});
frame.add(new JScrollPane(table1), BorderLayout.WEST);
frame.add(new JScrollPane(table2), BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
public class Person {
private final String firstName;
private final String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestSortedTable().initUI();
}
});
}
}
来源:https://stackoverflow.com/questions/14633909/selecting-a-row-on-a-jtable-shall-automatically-select-the-corresponding-row-on