2013-04-08 30 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(); 
    } 
}