我有一个名为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/