简体   繁体   中英

How to add MouseListener to a table model

I have a JTable. When a user clicks on a cell another JTable is created that shows the data for the whole row of that cell, in a column format (ie the row is converted to a column).

This happens when the user clicks but its a bit irritating to happen every time so I want to make it only on a double click.

The problem is that the getSelection method of the table only takes a addListSelectionListener method and not a MouseListener. How can I do what I want?

Here is the code:

public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    int selectedRow = table.getSelectedRow();
                    DefaultTableModel newModel = new DefaultTableModel();
                    String rowName = "Row: " + selectedRow;
                    newModel.setColumnIdentifiers(new Object[]{rowName});
                    for (int i = 0; i < table.getModel().getColumnCount(); i++) {
                        newModel.addRow(new Object[]{table.getModel().getValueAt(selectedRow, i)});
                    }
                    JTable newTable = new JTable(newModel) {
                        /**
                         * 
                         */
                        private static final long serialVersionUID = 1L;

                        @Override
                        public Dimension getPreferredScrollableViewportSize() {
                            return new Dimension(140, 240);
                        }
                    };

                    // Apply any custom renderers and editors
                    JOptionPane.showMessageDialog(frame, new JScrollPane(newTable),
                        rowName, JOptionPane.PLAIN_MESSAGE);
                }
            }
        });

This happens when the user clicks but its a bit irritating to happen every time so I want to make it only on a double click

You use a MouseListener , not a ListSelectionListener. You would check the Mouse event for a click count of 2.

Read the section from the Swing tutorial on How to Write a MouseLister for more information and working examples.

Also, a double click will start the editor by default so you want to make sure the cell is not editable. So you may need to override the isCellEditable(...) method of the table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM