java JTable select after sort

62 views Asked by At

I would like to ask for help in making a JTable, enabling the line, if a line is clicked, I read it. The problem would be that if I click on a line and then on the header (because of the sort), then the last choice appears, i.e. the modal comes up, etc. as if I had clicked on a line. Is there a solution for this or what did I do wrong? Thank you very much

my code:

`private void showUsersListInTable() {
    scrollPane.setVisible(true);
    scrollPane.getViewport().setSize(600, 500);
    userListTable.setSize(600, 500);
    getDataFromDB();
    reFreshTableData();
    tableModel = new DefaultTableModel(tableData, columnNames);

    userListTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    userListTable.setAutoCreateRowSorter(true);
    userListTable.setRowSelectionAllowed(true);
    userListTable.getSelectionModel().addListSelectionListener(e -> {

        if (!e.getValueIsAdjusting() && userListTable.getSelectedRow() != -1) {
            int a = userListTable.convertRowIndexToModel(userListTable.getSelectedRow());
            String email = userListTable.getModel().getValueAt(a, 2).toString();

            int i = 0;
            while (!users.get(i).getEmail().equals(email)) {
                i++;
            }
            User modifyUser = (i > users.size() || i < 0) ? new User("", "", "", "", 0, new UserRight(false, false)) : users.get(i);

            createDialog(modifyUser, frame);

        }

    });
    scrollPane.setViewportView(userListTable);
}`

my attempts:

set jtable header (wrong,IDE use red underline.), modify sort with if(userListTable.getSelectedRow() != 0)

1

There are 1 answers

0
camickr On

It appears the row selection event is generated because the selected row in the view row has changed when you sort a column.

You can manually track to see if the selected row in the model has changed:

import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.awt.*;
import java.util.*;

public class TableSelectionDemo2 extends JPanel
{
    private JTable table;
    private int previousSelectedRow = -1;

    public TableSelectionDemo2()
    {
        setLayout(new BorderLayout());

        String[] columnNames = {"Date", "String", "Integer", "Boolean"};
        Object[][] data =
        {
            {new Date(), "A", Integer.valueOf(1), Boolean.TRUE },
            {new Date(), "B", Integer.valueOf(2), Boolean.FALSE},
            {new Date(), "C", Integer.valueOf(19), Boolean.TRUE },
            {new Date(), "D", Integer.valueOf(4), Boolean.FALSE}
        };

        DefaultTableModel model = new DefaultTableModel(data, columnNames)
        {
            //  Returning the Class of each column will allow different
            //  renderers and editors to be used based on Class

            public Class getColumnClass(int column)
            {
                switch (column)
                {
                    case 0: return Date.class;
                    case 2: return Integer.class;
                    case 3: return Boolean.class;
                }

                return super.getColumnClass(column);
            }
        };

        table = new JTable(model);
        table.getSelectionModel().addListSelectionListener(new RowListener());
        table.setAutoCreateRowSorter(true);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        add(new JScrollPane(table));
    }

    private class RowListener implements ListSelectionListener
    {
        public void valueChanged(ListSelectionEvent event)
        {
            if (event.getValueIsAdjusting()) return;

            int selectedRow = table.convertRowIndexToModel(table.getSelectedRow());


            if (selectedRow == previousSelectedRow) return;

            // New selection, do processing

            System.out.println("Selected Row: " + selectedRow);
            previousSelectedRow = selectedRow;
        }
    }


    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("TableSelectionDemo2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        TableSelectionDemo2 newContentPane = new TableSelectionDemo2();
        frame.setContentPane(newContentPane);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Sorting does not affect the selected row in the model.