首页 > 解决方案 > 如何让 JTable 上的 MouseListener 正常工作

问题描述

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

我尝试new object在主要方法中使用a,然后创建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");
   }
}

在这段代码中,我期望一个printwith"clicked" 但我得到的只是这个错误 My Error TableIcon cannot be cast to java.awt.event.MouseListener

标签: javaswingjtableevent-listener

解决方案


您指的是this哪个是类TableIcon,它没有实现接口MouseListener,但方法addMouseListener()需要它。

public void addMouseListener(MouseListener l)

如果您也想使用TableIcon类作为事件处理程序的方法,请为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) {
 }

}

推荐阅读