如何在单元格编辑开始时关闭表格中的所有工具提示?

ete*_*00b 4 java swing jtable tooltip

我通过覆盖JTable继承的JComponent方法在我的JTable中启用了工具提示:

public String getToolTipText(MouseEvent e) { ... }
Run Code Online (Sandbox Code Playgroud)

现在,假设用户在一个单元格上盘旋,出现工具提示,然后他开始编辑单元格,我想强行关闭工具提示.

目前,工具提示只是挂起,直到我使用ToolTipManager #setDismissDelay指定的值到期.工具提示有时会模糊正在编辑的单元格的视图,这就是为什么我想在表格上的任何单元格进入编辑模式时忽略它.

我尝试了以下方法(这是伪代码)

public String getToolTipText(MouseEvent e)
{
    if(table-is-editing)
        return null;
    else
        return a-string-to-display-in-the-tooltip;
}
Run Code Online (Sandbox Code Playgroud)

当然,这只会在编辑模式下显示表格的工具提示非常好.我知道这不起作用,但更多的是在黑暗中拍摄.

cam*_*ckr 6

您可以使用以下代码显示/隐藏工具提示:

//Action toolTipAction = component.getActionMap().get("postTip");
Action toolTipAction = component.getActionMap().get("hideTip");

if (toolTipAction != null)
{
    ActionEvent ae = new ActionEvent(component, ActionEvent.ACTION_PERFORMED, "");
    toolTipAction.actionPerformed( ae );
}
Run Code Online (Sandbox Code Playgroud)

您可能会覆盖prepareCellEditor(...)JTable 的方法来添加此代码,它应该在显示编辑器之前隐藏任何工具提示.

编辑:

为了回应Kleopatra的评论,我添加以下内容以确保将Action添加到ActionMap:

table.getInputMap().put(KeyStroke.getKeyStroke("pressed F2"), "dummy");
ToolTipManager.sharedInstance().registerComponent( table );
Run Code Online (Sandbox Code Playgroud)


kle*_*tra 6

即将评论"你的错误" - 但是在没有隐藏起始编辑的工具提示的情况下可能会发生一个用例:-)

一些事实:

  • 工具提示隐藏在mouseExit和focusLost上使用ToolTipManager注册的组件
  • 当开始编辑并且编辑组件获得焦点时,工具提示会自动隐藏
  • 默认情况下,JTable中也不会产生焦点编辑组件编辑通过输入到单元格开始(由相双击或F2):在这种情况下,没有focusLost被激发,因此工具提示不是隐藏
  • ToolTipManager确实安装了一个可能被重用的hideAction(如@camickr所提到的).但是 - 仅当组件具有WHEN_FOCUSED类型的inputMap时才会安装该操作.JTable不是这种情况(所有绑定都在WHEN_ANCESTOR中)

因此需要进行一些调整才能实现所需的行为,下面是一段代码片段(请注意自己:在SwingX中实现:-)

JTable table = new JTable(new AncientSwingTeam()) {

    {
        // force the TooltipManager to install the hide action
        getInputMap().put(KeyStroke.getKeyStroke("ctrl A"), 
             "just some dummy binding in the focused InputMap");
        ToolTipManager.sharedInstance().registerComponent(this);

    }

    @Override
    public boolean editCellAt(int row, int column, EventObject e) {
        boolean editing = super.editCellAt(row, column, e);
        if (editing && hasFocus()) {
            hideToolTip();
        }
        return editing;
    }

    private void hideToolTip() {
        Action action = getActionMap().get("hideTip");
        if (action != null) {
            action.actionPerformed(new ActionEvent(
                this, ActionEvent.ACTION_PERFORMED, "myName"));
        }
    }

};
Run Code Online (Sandbox Code Playgroud)