java - 如何结合Swing和SpringFramework?

标签 java spring swing event-dispatch-thread

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/

相关文章:

java - 类型安全 : The expression of type List needs unchecked conversion to conform to Collection<? 扩展对​​象>

java - Play 请求中的模拟查询字符串

java - JUnitParamsRunner 与输入文件 - 字符串参数问题

java - 如何在 spring 配置中创建 javax.mail.Session

java - showInputDialog 卡住其他窗口

java - 具有独立于泛型类型的泛型方法的原始类型

java - Spring Security 空指针异常

java - Apache Camel : What is the best way to reuse Camel routes from other routes?

Java 和 JScrollPane : where to call setPreferredSize?

java - 简单,在java swing中包装红色验证消息