【问题标题】:Add mouse listener to JLabel in ListCellRenderer将鼠标监听器添加到 ListCellRenderer 中的 JLabel
【发布时间】:2012-03-14 13:11:13
【问题描述】:

我有一个由两个 JLabel 组成的 ListCellRenderer;一个用于文本,一个用于退出图像(一个小十字)。

我想在那个小十字上添加一个鼠标监听器,当单击时,该项目将从 JList 中删除。

【问题讨论】:

  • 向渲染组件添加监听器是没有意义的(它永远不是容器层次结构的一部分,因此永远不会看到任何事件)。而是将侦听器添加到列表中,并检查如果已添加组件以呈现该行,事件是否会在图标上方

标签: java swing jlist mouselistener listcellrenderer


【解决方案1】:

您可以尝试如下直接将 MouseListener 添加到您的 JList,

list.addMouseListener(new MouseAdapter(){
   public void mouseReleased(final MouseEvent e) {
         if (e.isPopupTrigger()) {               

             // Get the position of the click
              final int x = e.getX();
              final int y = e.getY();

              // Verify that the click occured on the selected cell
              final int index = list.getSelectedIndex();
          }
    }
});

现在根据上面的索引,您可以实现您想要做的。

【讨论】:

  • ehh .. popupTrigger 属性与问题有什么关系?
  • @kleopatra,感谢您指出错误,非常感谢。
猜你喜欢
  • 2012-08-01
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 2011-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多