When embedding a WinForms control in a Java application, execution freezes when a CommonDialog (e.g., OpenFileDialog, SaveFileDialog) comes up
Situation: You have created a Java application that contains a Windows Forms control. When you perform some action that executes .NET code to display a WinForms CommonDialog (a set of dialogs including OpenFileDialog, SaveFileDialog, and FolderBrowserDialog, among others), the executing thread freezes when the ShowDialog() method is called.
CommonDialogs are basically COM objects that require the single-threaded apartment model. If your .NET side is configured to use the multi-threaded apartment model (the default), execution will usually freeze when ShowDialog() is called. (Note that there are some exceptions to this, but you should always code under the assumption that execution will freeze in this situation.)
To resolve this problem, add the dotNetSide.apartmentThreadingModel property to your Java-side configuration, and set it to “STA”. For example, if you are using a properties file for configuration, add
dotNetSide.apartmentThreadingModel=STA
In a few cases, simply adding this property will not work, in which case, add the following line to the constructor of your WinForms control (it should be the first line, before the call to InitializeComponents()):
System.Threading.Thread.CurrentThread.SetApartmentState(System.Threading.ApartmentState.STA);