工具提示中的JPanel JTable中不工作(Tool tip in JPanel in JTab

2019-09-17 17:20发布

我有一个JTable 。 一列拥有JPanel其中包含一些JLabelsImageIcons 。 我创建了一个自定义单元格渲染和一切工作正常除在刀尖JLabel 。 当我鼠标移到这些中JLabels我需要显示Tooltip特定的JLabel 。 它没有显示的tootlip JLabel

这里是CustomRenderer

private class CustomRenderer extends
            DefaultTableCellRenderer implements TableCellRenderer {

        @Override
        public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus, int row,
                int column) {   

            if (value != null && value instanceof List) {

                JPanel iconsPanel = new JPanel(new GridBagLayout());
                List<ImageIcon> iconList = (List<ImageIcon>) value;
                int xPos = 0;
                for (ImageIcon icon : iconList) {
                    JLabel iconLabel = new JLabel(icon);
                    iconLabel.setToolTipText(icon.getDescription());
                    GridBagConstraints gbc = new GridBagConstraints();
                    gbc.gridy = 1;
                    gbc.gridx = xPos++;
                    iconsPanel.add(iconLabel, gbc);
                }
                iconsPanel.setBackground(isSelected ? table
                        .getSelectionBackground() : table.getBackground());
                this.setVerticalAlignment(CENTER);
                return iconsPanel;
            }
            return this;
        }
    }

Answer 1:

问题是,你在你的CellRenderer返回的组件的子集提示。 要执行你想要什么,你应该考虑覆盖getToolTipText(MouseEvent e)在JTable中。 从事件,你可以找到关于该行和列的鼠标,使用:

java.awt.Point p = e.getPoint();
int rowIndex = rowAtPoint(p);
int colIndex = columnAtPoint(p);

从那里,你可以再重新准备的单元格渲染器,找到哪个部件位于鼠标的位置,并最终取得其提示。

这里是你如何可以覆盖JTable的getToolTipText一个片段:

@Override
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);
        Rectangle cellRect = getCellRect(hitRowIndex, hitColumnIndex, false);
        component.setBounds(cellRect);
        component.validate();
        component.doLayout();
        p.translate(-cellRect.x, -cellRect.y);
        Component comp = component.getComponentAt(p);
        if (comp instanceof JComponent) {
            return ((JComponent) comp).getToolTipText();
        }
    }

    // No tip from the renderer get our own tip
    if (tip == null) {
        tip = getToolTipText();
    }

    return tip;
}


文章来源: Tool tip in JPanel in JTable not working