如何让 JTable 上的 MouseListener 正常工作

How do I get the MouseListener on a JTable working

我正在尝试让 JTableMouseListener 一起工作。 现在的代码是带有图标的 JTable 的示例程序。 我想要的是,如果您 双击 一行,dialog 应该打开 整行 的信息或者只是行中的 index-number。 但我的问题是命令:table.addMouseListener(this); 不起作用,也许是因为构造函数?

我尝试在 main 方法中使用 new object 然后创建 MousListener。

 public class TableIcon extends JPanel
 {
   public TableIcon()
   {
       Icon aboutIcon = new ImageIcon("Mypath");
       Icon addIcon = new ImageIcon("Mypath");
       Icon copyIcon = new ImageIcon("Mypath");

       String[] columnNames = {"Picture", "Description"};
       Object[][] data =
       {
           {aboutIcon, "Pic1"},
           {addIcon, "Pic2"},
           {copyIcon, "Pic3"},
       };

       DefaultTableModel model = new DefaultTableModel(data,columnNames)
       {
           public Class getColumnClass(int column)
           {
               return getValueAt(0, column).getClass();
           }

           public boolean isCellEditable(int row, int column)
           {
               return false;
           }

       };
       JTable table = new JTable( model );
       table.setPreferredScrollableViewportSize
           (table.getPreferredSize());
 // ################ MyError #########
       table.addMouseListener(this); // Error
 // ##################################
       JScrollPane scrollPane = new JScrollPane( table );
       add( scrollPane );  
   }

   private static void createAndShowGUI()
   {
       TableIcon test = new TableIcon();

       JFrame frame = new JFrame("Table Icon");
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.add(test);
       frame.setLocationByPlatform( true );
       frame.pack();
       frame.setVisible( true );
   }

   public static void main(String[] args)
   {
       EventQueue.invokeLater(new Runnable()
       {
           public void run()
           {
               createAndShowGUI();
           }
       });
   }
   public void mouseClicked(MouseEvent e)
   {
       System.out.println("clicked");
   }
}

在这段代码中,我期望 print 和 "clicked" 但我得到的只是这个错误 我的错误 TableIcon 无法转换为 java.awt.event.MouseListener

尝试使用适配器 class:

table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
      if (e.getClickCount() == 2) {
        //Code for handling the double click event
      }
    }
});

您引用 this,它是 class TableIcon,它没有实现接口 MouseListener,但方法 addMouseListener() 需要它。

public void addMouseListener(MouseListener l)

如果您想采用 TableIcon class 的方法也充当事件处理程序,则添加 MouseListener 接口的实现。

public class TableIcon extends JPanel implements MouseListener {

 ...

 public void mouseClicked(MouseEvent e) {
    // code for handling of the click event
 }

 public void mouseEntered(MouseEvent e) {
 }

 public void mouseExited(MouseEvent e) {
 }

 public void mousePressed(MouseEvent e) {
 }

 public void mouseReleased(MouseEvent e) {
 }

}