开发者

Show a tooltip above a cell in a JTable

I need to show a tooltip above (or below :) a cell when the user enter a wrong value in it (see the image below). I have a tooltip, but I need a Point to display it at the right position, so I want to get a cell开发者_如何学JAVA position. Do you know how to get this?

BUT, if you have a better solution to realize this behaviour, I'm open to all proposition (especially for the fact that the tooltip is not bind with the cell/Jtable/Panel and if I move/close/minmize my window the tooltip is display at the same position)

Show a tooltip above a cell in a JTable

Thanks, Damien


Please refer below code snippet, and you'll get the solution

JTable table = new JTable() {
    public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
        Component c = super.prepareRenderer(renderer, row, column);
        if (c instanceof JComponent) {
            JComponent jc = (JComponent) c;
            jc.setToolTipText(getValueAt(row, column).toString());
        }
        return c;
    }
};

If you want to only show the specific cell, all you have to do is change the column param in the params of getValueAt(...) method to a specific column which contains that cell


You have an example of such feature in the Swing components visual guide.

Edit: In fact, it is not really a tooltip that you need here, as the tooltip need to have the cursor positionned over the cell. You want to display the tooltip even if the cursor is outside the cell, right?

Anyway, an alternative solution is to change the background of the cell when the value entered by the user is invalid (in orange or red for example), and then add a "real" tooltip (using the link I provided) in order to give the user a complete error message.


Just use below code while creation of JTable object.

JTable auditTable = new JTable(){

            //Implement table cell tool tips.           
            public String getToolTipText(MouseEvent e) {
                String tip = null;
                java.awt.Point p = e.getPoint();
                int rowIndex = rowAtPoint(p);
                int colIndex = columnAtPoint(p);

                try {
                    //comment row, exclude heading
                    if(rowIndex != 0){
                      tip = getValueAt(rowIndex, colIndex).toString();
                    }
                } catch (RuntimeException e1) {
                    //catch null pointer exception if mouse is over an empty line
                }

                return tip;
            }
        };


Try getCellRect


Use the following code to get the value for the correct row if using RowSorter:

jc.setToolTipText(getValueAt(convertRowIndexToModel(row), column).toString());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜