2013-04-08 57 views
1

一定ammount的取消之后在JList一个项目我有当在列表中的项目的用户点击,它会保持选定一个所谓的jList todoList如何毫秒的一个mouseExit事件

。但是我希望列表中当前选定的项目在鼠标退出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()方法。每次鼠标退出列表时,都会发生这种情况,并且只有在列表中已经选择了某些内容的情况下才会运行。

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

回答

3

问题是,Object#wait正在等待(而不是睡觉)被通知,但这不会发生。相反,超时会导致InterruptedException跳过clearSelection的呼叫。

请勿在Swing应用程序中使用原始Threads。请使用专门用于与Swing组件交互的Swing Timer

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

注意,从我复制的代码不能正常工作,我忘了补充'。开始()'和其他一些东西;) – 2013-04-08 20:40:37

+0

谢谢。修复编译错误(请参阅rev history),因此它是正确的。编辑后的+1。 – 2013-04-08 20:46:17

+0

非常感谢你们!现在有道理。 – 2013-04-09 07:30:22

4

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