我有一个带有ContextMenu insight Task的静态BorderPane
Task task = new Task()
{
@Override
protected Void call() throws Exception
{
Platform.runLater(new Runnable()
{
@Override
public void run()
{
try
{
contextMenu = new ContextMenu();
MenuItem item1 = new MenuItem("About");
item1.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
System.out.println("About");
}
});
MenuItem item2 = new MenuItem("Preferences");
item2.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
System.out.println("Preferences");
}
});
MenuItem item3 = new MenuItem("Close");
item3.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
}
});
contextMenu.getItems().addAll(item1, item2, item3);
bp.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>()
{
@Override
public void handle(ContextMenuEvent event)
{
contextMenu.show(bp, event.getScreenX(), event.getScreenY());
event.consume();
}
});
bp.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent event)
{
contextMenu.hide();
}
});
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
}
}
});
return null;
}
};
new Thread(task).start();
我注意到当我关闭保存BorderPane的组件时,Java线程没有被释放,它们仍然被初始化到内存中。我不确定这是由静态BorderPane引起的。任务完成后,应该处理Java线程。知道为什么会这样吗?
答案 0 :(得分:2)
问题不是Task
,而是Runnable
中的匿名类。
在下一段代码中:
bp.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>()
{
@Override
public void handle(ContextMenuEvent event) {
//...
}
});
你引入了一个扩展EventHandler
的匿名类,它保存了Runnable
的内部链接。要解决此问题,您可以使用nested 静态类。
P.S。:很遗憾,您无法在Java中创建匿名类静态,请参阅Is it possible to make anonymous inner classes in Java static?