java - 如何在鼠标退出事件一定毫秒数后取消选择 jList 中的项目

标签 java swing timer jlist listselectionlistener

我有一个名为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() 方法。每次鼠标退出列表时都会发生这种情况,并且仅当列表中的内容已被选中时才会运行。

我希望我已经足够彻底地解释了我的问题。

最佳答案

问题是您阻止了 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();
    }
}

关于java - 如何在鼠标退出事件一定毫秒数后取消选择 jList 中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15888244/

相关文章:

java - Java 如何自动回答用户提示?

java - Spring MockMvc - 从 REST 获取 java.time.Instant

c - 使用定时器中断使 LED 闪烁(atmega 128)

c# - 关闭应用程序的计时器

java - 在 Spark Cassandra 连接器中映射 UUID

java - Retrofit2 POST 请求响应返回null

java - 尝试创建多个 JLabel,但只出现一个

java - 覆盖 Nimbus 颜色

java - 获取已添加到 JFrame 中的按钮

c# - Timer Job 是这项工作的正确工具吗?