【问题标题】:How to deselect an item in a jList after a certain ammount of milliseconds on a mouseExit event如何在鼠标退出事件的一定毫秒数后取消选择 jList 中的项目
【发布时间】:2013-03-31 01:47:32
【问题描述】:

我有一个名为todoList的jList

当用户单击列表中的某个项目时,它会保持选中状态。但是我希望列表中当前选定的项目在鼠标退出 jList 时在 400 毫秒后“自行”取消选择。

只有在列表中已经选择了某些内容时才能运行。

我正在使用 Netbeans IDE,这是迄今为止尝试过的:

private void todoListMouseExited(java.awt.event.MouseEvent evt) {                                     
    if (!todoList.isSelectionEmpty()) {
        Thread thread = new Thread();
        try {
            thread.wait(400L);
            todoList.clearSelection();
        } catch (InterruptedException ex) {
            System.out.println(ex);
        }
    }
}

 private void todoListMouseExited(java.awt.event.MouseEvent evt) {                                     
    if (!todoList.isSelectionEmpty()) {
        Thread thread= Thread.currentThread();
        try {
            thread.wait(400L);
            todoList.clearSelection();
        } catch (InterruptedException ex) {
            System.out.println(ex);
        }
    }
}

这些都只是让一切都停止工作。

我的过程是我需要创建一个等待 400 毫秒的新线程,然后运行 ​​jList 的 clearSelection() 方法。每次鼠标退出列表时都会发生这种情况,并且仅当列表中有已被选中的内容时才会运行。

我希望我能彻底解释我的问题。

【问题讨论】:

    标签: java swing timer jlist listselectionlistener


    【解决方案1】:

    问题在于Object#wait 正在等待(而不是睡眠)收到通知,但这并没有发生。相反,超时导致InterruptedException 绕过对clearSelection 的调用。

    不要在Swing 应用程序中使用原始Threads。请改用 Swing Timer,它旨在与 Swing 组件交互。

    if (!todoList.isSelectionEmpty()) {
       Timer timer = new Timer(400, new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
             todoList.clearSelection();
          }
       });
       timer.setRepeats(false);
       timer.start();
    }
    

    【讨论】:

    • 请注意,我复制的代码不起作用,我忘了添加.start()和其他一些东西;)
    • 谢谢。修复编译错误(见版本历史),所以它是正确的。编辑后 +1。
    • 我用过这个,它可以工作,但并不完美。当我单击列表上的项目并且我的鼠标退出列表时,该项目会按原样取消选择,但是当我尝试再次单击该项目时,它甚至没有选择。我认为这是因为计时器在 400 毫秒后没有停止,所以 ActionListener 搞砸了。我在public void actionPerformed 中使用了System.out.println(e);,输出为java.awt.event.ActionEvent[unknown type,cmd=null,when=1365513320800,modifiers=] on javax.swing.Timer@aba647。你能再帮我一次吗?
    • 我不能投票,因为我需要 15 分 :( 否则我会投票的!
    • @Reimeus 对不起,我只有最后一个问题。当鼠标进入列表时,有没有办法停止计时器?如果鼠标在列表中,我不希望取消选择该项目。
    【解决方案2】:

    问题是您阻塞了 AWT-Event-Thread。

    解决方案是使用swing timer:

    private void todoListMouseExited(java.awt.event.MouseEvent evt) 
    {
       if (!todoList.isSelectionEmpty()) {
            new Timer(400, new ActionListener() {
                  public void actionPerformed(ActionEvent evt) {
                      todoList.clearSelection();
                  }
            }).start();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-24
      • 2023-04-02
      • 1970-01-01
      • 2011-02-01
      • 2013-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多