Whenever I'm prototyping Swing code, there's lots to remember about getting a component on screen:
invokeLater() for thread safety
setDefaultCloseOperation() to clean up after myself
pack() and setLocationRelativeTo() for a convenient frame
To make this easier, I've created a Live Template for IDEA. Add this to your collection of live templates, then simply type swing[tab] and remove a little more boilerplate from your life!
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() { public void run() {
JPanel panel = new JPanel(new BorderLayout());
$FOCUS$
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}});
}
2 comments:
Awesome. I'd been typing the same stuff in a few times over the past few days and had been feeling a little unhappy about it. Combined with the way my eye starts to twitch every time I have to type frame.getContentPane() it's nice to have a template.
You can do the same thing in eclipse by opening Window->Preferences>Java>Editor->Templates and adding one like this
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() { public void run() {
JPanel panel = new JPanel(new BorderLayout());
${cursor}
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}});
}
Hi. Why don't you (also) make an utility method/class out of this?
/karolrvn
Post a Comment