Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9218797
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T02:56:47+00:00 2026-06-18T02:56:47+00:00

I have a problem with the selection of rows on my JTable instances. This

  • 0

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 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T02:56:48+00:00Added an answer on June 18, 2026 at 2:56 am

    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();
                }
            });
        }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a problem with element selection, i have a form and i want
I use emacs 24 (OSX) and have a problem with shift-selection. If I select
i have a small problem i have xome xml with a cdata section. This
I have a little problem with a query. I'm selecting data using the between
I have a UITableViewController (MyViewController.xib). This is showing 3 rows with their title. I
I have a scenario where I want to show hierarchical data in a DataGrid
I have problem removing rows from a table according to the checkbox. Below is
I have an optimisation problem with a fairly large table (~1.7M rows). There are
I have a listview with some rows. These rows contain a textbox. I would
I have a pickerView and depending on the selection in that pickerView i want

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.