Java Swing Test Frame

This post has nothing to do with poker.

I often need to test a specific aspect of Java’s Swing GUI toolkit to reproduce a problem. In order to help me and others avoid having to rewrite boiler-plate code to make the smallest possible reproduction case, I’m posting the basic code I use here. Consider it an easily-found memo to myself:



import javax.swing.*;
import java.awt.*;

public class SwingTestFrame {

public static void main(String[] args) {
createAndLaunchGui();
}

private static void createAndLaunchGui() {
// UIManager.setLookAndFeel throws "nothing we can do about it" style exceptions. Best thing to do is
// to wrap as an unchecked exception
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
throw new RuntimeException(e);
}

// using invoke later avoids possible obscure phantom timing issues
// as (almost) all GUI code should be run on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JFrame frame = new JFrame("Java Swing Test Frame");

// when the close window control is clicked, we want the app to exit
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// using a panel as a top level component to hold all other GUI controls is a flexible approach
final JPanel panel = new JPanel();
addComponentsToPanel(panel);
frame.getContentPane().add(panel);

frame.setPreferredSize(new Dimension(600, 400));
// pack layouts the frame according to the current LayoutManager
frame.pack();
// setLocationRelativeTo(null) centres the frame
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

// modify this to build your GUI
private static void addComponentsToPanel(JPanel panel) {
panel.add(new JLabel("Hello cruel world"));
panel.add(new JButton("Do Stuff"));
}


}

Once more without most comments:



import javax.swing.*;
import java.awt.*;

public class SwingTestFrame {

public static void main(String[] args) {
createAndLaunchGui();
}

private static void createAndLaunchGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
throw new RuntimeException(e);
}

SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JFrame frame = new JFrame("Java Swing Test Frame");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final JPanel panel = new JPanel();
addComponentsToPanel(panel);
frame.getContentPane().add(panel);

frame.setPreferredSize(new Dimension(600, 400));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

// modify this to build your GUI
private static void addComponentsToPanel(JPanel panel) {
panel.add(new JLabel("Hello cruel world"));
panel.add(new JButton("Do Stuff"));
}


}