【问题标题】:JPanel in JTable gets focus on mouse click but not on mouse overJTable 中的 JPanel 专注于鼠标点击而不是鼠标悬停
【发布时间】:2012-05-14 07:42:38
【问题描述】:

我有一个表,其中一列包含 JPanel。我已经编写了自定义渲染器和编辑器,它们工作正常。但是,该面板包含一个带有工具提示的 JLabel 组件。如果我单击单元格并将鼠标悬停在标签上,则会显示工具提示,但如果我将鼠标移入单元格并将鼠标悬停在 JLabel 上,则不会显示工具提示。我在表格中添加了一个鼠标侦听器,如下所示,我在其中获取 Panel 对象并尝试使其具有焦点。

public void mouseMoved(MouseEvent e) {
    Point p = e.getPoint();
    int row = table.rowAtPoint(p);
    int column = table.columnAtPoint(p);
    System.out.println(row + " " + column);
    Object o = table.getModel().getValueAt(row, column);
    if (o instanceof FileInfoCellPanel) {
        FileInfoCellPanel ficp = (FileInfoCellPanel)o;
        ficp.requestFocusInWindow();
        //ficp.revalidate();
    }
}

我肯定得到了正确的 JPanel 对象,但它似乎从未获得焦点。因此,单击单元格似乎可以将焦点集中到面板上,但移动鼠标却没有。

【问题讨论】:

    标签: java swing jtable mouselistener


    【解决方案1】:

    如果您只想在工具提示中显示文本,则在渲染器返回的组件上设置工具提示就足够了。这可以看我下面复制的JTable#getTooltipText方法的实现

    public String getToolTipText(MouseEvent event) {
        String tip = null;
        Point p = event.getPoint();
    
        // Locate the renderer under the event location
        int hitColumnIndex = columnAtPoint(p);
        int hitRowIndex = rowAtPoint(p);
    
        if ((hitColumnIndex != -1) && (hitRowIndex != -1)) {
            TableCellRenderer renderer = getCellRenderer(hitRowIndex, hitColumnIndex);
            Component component = prepareRenderer(renderer, hitRowIndex, hitColumnIndex);
    
            // Now have to see if the component is a JComponent before
            // getting the tip
            if (component instanceof JComponent) {
                // Convert the event to the renderer's coordinate system
                Rectangle cellRect = getCellRect(hitRowIndex, hitColumnIndex, false);
                p.translate(-cellRect.x, -cellRect.y);
                MouseEvent newEvent = new MouseEvent(component, event.getID(),
                                          event.getWhen(), event.getModifiers(),
                                          p.x, p.y,
                                          event.getXOnScreen(),
                                          event.getYOnScreen(),
                                          event.getClickCount(),
                                          event.isPopupTrigger(),
                                          MouseEvent.NOBUTTON);
    
                tip = ((JComponent)component).getToolTipText(newEvent);
            }
        }
    
        // No tip from the renderer get our own tip
        if (tip == null)
            tip = getToolTipText();
    
        return tip;
    }
    

    可以看出,为了确定工具提示文本,渲染器被要求提供一个组件,并且该组件被要求提供其工具提示文本。当然,这仅适用于文本,而不适用于例如图片

    【讨论】:

      猜你喜欢
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      • 2018-09-03
      • 1970-01-01
      相关资源
      最近更新 更多