Posted by Darryl Burke on November 13, 2008
The standard SwingUtilities class has almost too many methods to count, including 4 that return various ancestors of a component. Alas, the only method of some use to obtain a descendant, getDeepestComponentAt(…) is useful only in the context of a MouseListener.
SwingUtils attempts to provide methods for obtaining a reference to nested components, together with some for obtaining the properties and UIDefaults pertaining to a component.
The methods of the class fall in four broad groupings:
- getDescendant(s)OfType return component(s) of a specified class including component(s) of named or anonymous subclasses.
- getDescendant(s)OfClass return component(s) of the specified class only
- getUIDefault(s)OfClass return a subset of the UIDefaults for a particular class or a single value for a particular property.
- getJClass returns the nearest javax.swing superclass of a derived component, getProperties returns a Map of non-null, human-readable properties of a component and equals determines whether two objects are either equal or both null.
The getDescendants… methods of SwingUtils are especially useful for obtaining a reference to a contained component of a complex widget like JComboBox or JFileChooser. This line of code will return a reference to the arrow button of a JComboBox:
JButton button = SwingUtils.getDescendantsOfType(JButton.class, jComboBox).get(0);
This shows how to disable the text field of a JFileChooser to ensure the user can open only a listed file:
JFileChooser jFileChooser = new JFileChooser();
JTextField jTextField = SwingUtils.getDescendantOfType(
JTextField.class, jFileChooser, "Text", "");
These methods can be equally useful for obtaining references to components in your own or third-party GUIs and may be a convenient alternative to providing accessors for components, especially when the component to be accessed will be identified by a runtime property.
The remaining methods are more in the nature of investigative tools to aid in designing and troubleshooting a Swing GUI.