rspec/rules/S3035/java/rule.adoc
2021-04-28 16:49:39 +02:00

37 lines
871 B
Plaintext

Swing interfaces should be constructed and shown from the Swing event dispatch thread. Doing so from any other thread, such as from ``++main++`` risks deadlocks since you run the risk of multiple threads accessing things which are inherently not thread-safe.
Instead, use ``++SwingUtilities.invokeLater++`` or ``++SwingUtilities.invokeAndWait++`` to kick off a ``++new Runnable++`` that handles your GUI creation.
== Noncompliant Code Example
----
public static void main(String args[]) {
makeGui(); // Noncompliant
}
public void makeGui() {
JFrame frame = new JFrame();
// ...
frame.show();
}
----
== Compliant Solution
----
public static void main(String args[]) {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
makeGui();
}
}
}
public void makeGui() {
JFrame frame = new JFrame();
// ...
frame.show();
}
----