gpt4 book ai didi

java - 如何结合Swing和SpringFramework?

转载 作者:搜寻专家 更新时间:2023-10-31 20:33:52 26 4
gpt4 key购买 nike

Swing 需要从事件调度线程 (EDT) 中运行。如何在 Spring 上下文中确保这一点?

在一些教程中,like this one ,swing 组件只是像普通 bean 一样被实例化。这样可以吗?

最佳答案

正如您已经猜到的那样,在 Event Dispatching ThreadEDT 中运行您的 Swing 代码会更安全,因为大多数Swing 组件不是线程安全的。以下是 Oracle 文档中的说明:

Swing event handling code runs on a special thread known as the event dispatch thread. Most code that invokes Swing methods also runs on this thread. This is necessary because most Swing object methods are not "thread safe": invoking them from multiple threads risks thread interference or memory consistency errors.

因此,如果您在 EDT 线程中初始化您的 Spring ApplicationContext 以便您的组件在同一个线程中初始化和运行,那么您应该是安全的:

SwingUtilities.invokeLater(new Runnable() 
{
public void run()
{
new ClassPathXmlApplicationContext( "your-application-context.xml" ); // pay attention to context so that it is not left open
}
});

关于java - 如何结合Swing和SpringFramework?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28851811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com