Swing Programming Tips

Drag and Drop - a page describing essential concepts and tips for implementing non-trivial drag and drop in Java GUIs.

Layout Managers

Default layout manager of the content panel of a JFrame, JWindow and JDialog is: BorderLayout

Default layout manager of a JPanel is: flow layout

The box layout will attempt to set each child at the height(or width) of the tallest (or widest) child. (essentially the same as a GridLayout)

SpringLayout can be very handy and easy to use to arrange labels and JTextFields, but it (makeCompactGrid) malfunctions with JComboBox components (perhaps only a Java 5 bug?).

JLabel

setBackground(color) doesn't "work" on JLabel. This is because JLabel's are transparent. Thus to get a background for a JLabel you need to call setOpaque(true) or override paint() or place the JLabel on a JPanel and set the background color on the JPanel.

Swing's "default grey" under Windows Classic Look and Feel is RGB: 212, 208,200

Swing & Threads

Use javax.swing.SwingUtilities.isEventDispatchThread() to test if the current thread is the event dispatch thread or not.

Java can be very troublesome in that a nice fixed sequence of instructions can execute and yet there can be no change to the display! Very mysterious to the novice programmer! Sun has long explanations about Swing and threading and they introduce the concept of the "SwingWorker" class (not provided as part of Java) to deal with some of these problems.

To summarize this issue simply: the programmer virtually can not update the GUI except in the Swing thread (this essentially means only within an actionPerformed method).

To bypass this problem I sometimes create a dummy ActionEvent, illustrated by this code:

  ActionEvent myAE = new ActionEvent(someComponent,ActionEvent.ACTION_PERFORMED,"none");
this.actionPerformed(myAE); // trigger a Swing update!

 

JTable