如何将MouseListener添加到表模型

问题描述:

我有一个JTable。当用户单击单元格时,将创建另一个JTable,该列表以列格式显示该单元格整行的数据(即将行转换为列)。如何将MouseListener添加到表模型

这种情况发生在用户点击时,但每次都有点刺激,所以我只想双击它。

问题是表的getSelection方法只采用addListSelectionListener方法而不是MouseListener。我该怎么做我想要的?

下面是代码:

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); 
       } 
      } 
     }); 

这种情况发生在用户点击,但它有点刺激性发生的每一次,所以我希望把它仅在双击

您使用MouseListener,而不是ListSelectionListener。您可以检查鼠标事件的点击次数为2.

有关更多信息和工作示例,请参阅Swing教程中有关How to Write a MouseLister的部分。

此外,双击将默认启动编辑器,因此您要确保单元格不可编辑。所以你可能需要重写表的isCellEditable(...)方法。