Package javax.swing
Swing's Threading Policy
In general Swing is not thread safe. All Swing components and related classes, unless otherwise documented, must be accessed on the event dispatching thread.
Typical Swing applications do processing in response to an event generated
from a user gesture. For example, clicking on a JButton notifies all
ActionListeners added to the JButton. As all events generated
from a user gesture are dispatched on the event dispatching thread, most
developers are not impacted by the restriction.
Where the impact lies, however, is in constructing and showing a Swing
application. Calls to an application's main method, or methods in
Applet, are not invoked on the event dispatching thread. As such,
care must be taken to transfer control to the event dispatching thread when
constructing and showing an application or applet. The preferred way to
transfer control and begin working with Swing is to use invokeLater.
The invokeLater method schedules a Runnable to be processed
on the event dispatching thread. The following two examples work equally well
for transferring control and starting up a Swing application:
import javax.swing.SwingUtilities;
public class MyApp implements Runnable {
public void run() {
// Invoked on the event dispatching thread.
// Construct and show GUI.
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new MyApp());
}
}
Or:
import javax.swing.SwingUtilities;
public class MyApp {
MyApp(String[] args) {
// Invoked on the event dispatching thread.
// Do any initialization here.
}
public void show() {
// Show the UI.
}
public static void main(final String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyApp(args).show();
}
});
}
}
This restriction also applies to models attached to Swing components. For
example, if a TableModel is attached to a JTable, the
TableModel should only be modified on the event dispatching thread.
If you modify the model on a separate thread you run the risk of exceptions
and possible display corruption.
Although it is generally safe to make updates to the UI immediately,
when executing on the event dispatch thread, there is an exception :
if a model listener tries to further change the UI before the UI has been
updated to reflect a pending change then the UI may render incorrectly.
This can happen if an application installed listener needs to update the UI
in response to an event which will cause a change in the model structure.
It is important to first allow component installed listeners to process this
change, since there is no guarantee of the order in which listeners may be
called.
The solution is for the application listener to make the change using
SwingUtilities.invokeLater so that any changes to UI rendering will
be done post processing all the model listeners installed by the component.
As all events are delivered on the event dispatching thread, care must be
taken in event processing. In particular, a long running task, such as
network io or computational intensive processing, executed on the event
dispatching thread blocks the event dispatching thread from dispatching any
other events. While the event dispatching thread is blocked the application
is completely unresponsive to user input. Refer to
SwingWorker for the preferred way to do such processing
when working with Swing.
More information on this topic can be found in the Swing tutorial, in particular the section on Concurrency in Swing.
Related Documentation
For overviews, tutorials, examples, guides, and other documentation, please see:- The Swing Connection
- The Java Tutorial
- Online Training at the Java Developer Connection SM
- Java Foundation Classes (JFC) home page
-
Interface Summary Interface Description Action TheActioninterface provides a useful extension to theActionListenerinterface in cases where the same functionality may be accessed by several controls.BoundedRangeModel Defines the data model used by components likeSliders andProgressBars.ButtonModel State model for buttons.CellEditor This interface defines the methods any general editor should be able to implement.ComboBoxEditor The editor component used for JComboBox components.ComboBoxModel<E> A data model for a combo box.DesktopManager DesktopManager objects are owned by a JDesktopPane object.Icon A small fixed size picture, typically used to decorate components.JComboBox.KeySelectionManager The interface that defines aKeySelectionManager.ListCellRenderer<E> Identifies components that can be used as "rubber stamps" to paint the cells in a JList.ListModel<E> This interface defines the methods components like JList use to get the value of each cell in a list and the length of the list.ListSelectionModel This interface represents the current state of the selection for any of the components that display a list of values with stable indices.MenuElement Any component that can be placed into a menu should implement this interface.MutableComboBoxModel<E> A mutable version ofComboBoxModel.Painter<T> A painting delegate.Renderer Defines the requirements for an object responsible for "rendering" (displaying) a value.RootPaneContainer This interface is implemented by components that have a single JRootPane child: JDialog, JFrame, JWindow, JApplet, JInternalFrame.Scrollable An interface that provides information to a scrolling container like JScrollPane.ScrollPaneConstants Constants used with the JScrollPane component.SingleSelectionModel A model that supports at most one indexed selection.SpinnerModel A model for a potentially unbounded sequence of object values.SwingConstants A collection of constants generally used for positioning and orienting components on the screen.UIClientPropertyKey This interface is used only for tagging keys for client properties forJComponentset by UI which needs to be cleared on L&F change and serialization.UIDefaults.ActiveValue This class enables one to store an entry in the defaults table that's constructed each time it's looked up with one of thegetXXX(key)methods.UIDefaults.LazyValue This class enables one to store an entry in the defaults table that isn't constructed until the first time it's looked up with one of thegetXXX(key)methods.WindowConstants Constants used to control the window-closing operation. -
Class Summary Class Description AbstractAction This class provides default implementations for the JFCActioninterface.AbstractButton Defines common behaviors for buttons and menu items.AbstractCellEditor A base class forCellEditors, providing default implementations for the methods in theCellEditorinterface exceptgetCellEditorValue().AbstractListModel<E> The abstract definition for the data model that provides aListwith its contents.AbstractSpinnerModel This class provides the ChangeListener part of the SpinnerModel interface that should be suitable for most concrete SpinnerModel implementations.ActionMap ActionMapprovides mappings fromObjects (called keys orActionnames) toActions.BorderFactory Factory class for vending standardBorderobjects.Box A lightweight container that uses a BoxLayout object as its layout manager.Box.Filler An implementation of a lightweight component that participates in layout but has no view.BoxLayout A layout manager that allows multiple components to be laid out either vertically or horizontally.ButtonGroup This class is used to create a multiple-exclusion scope for a set of buttons.CellRendererPane This class is inserted in between cell renderers and the components that use them.ComponentInputMap AComponentInputMapis anInputMapassociated with a particularJComponent.DebugGraphics Graphics subclass supporting graphics debugging.DefaultBoundedRangeModel A generic implementation of BoundedRangeModel.DefaultButtonModel The default implementation of aButtoncomponent's data model.DefaultCellEditor The default editor for table and tree cells.DefaultComboBoxModel<E> The default model for combo boxes.DefaultDesktopManager This is an implementation of theDesktopManager.DefaultFocusManager This class has been obsoleted by the 1.4 focus APIs.DefaultListCellRenderer Renders an item in a list.DefaultListCellRenderer.UIResource A subclass of DefaultListCellRenderer that implements UIResource.DefaultListModel<E> This class loosely implements thejava.util.VectorAPI, in that it implements the 1.1.x version ofjava.util.Vector, has no collection class support, and notifies theListDataListeners when changes occur.DefaultListSelectionModel Default data model for list selections.DefaultRowSorter<M,I> An implementation ofRowSorterthat provides sorting and filtering around a grid-based data model.DefaultRowSorter.ModelWrapper<M,I> DefaultRowSorter.ModelWrapperis responsible for providing the data that gets sorted byDefaultRowSorter.DefaultSingleSelectionModel A generic implementation of SingleSelectionModel.FocusManager This class has been obsoleted by the 1.4 focus APIs.GrayFilter An image filter that "disables" an image by turning it into a grayscale image, and brightening the pixels in the image.GroupLayout GroupLayoutis aLayoutManagerthat hierarchically groups components in order to position them in aContainer.ImageIcon An implementation of the Icon interface that paints Icons from Images.InputMap InputMapprovides a binding between an input event (currently onlyKeyStrokes are used) and anObject.InputVerifier This class provides the validation mechanism for Swing components.InternalFrameFocusTraversalPolicy A FocusTraversalPolicy which can optionally provide an algorithm for determining a JInternalFrame's initial Component.JApplet Deprecated. The Applet API is deprecated, no replacement.JButton An implementation of a "push" button.JCheckBox An implementation of a check box -- an item that can be selected or deselected, and which displays its state to the user.JCheckBoxMenuItem A menu item that can be selected or deselected.JColorChooser JColorChooserprovides a pane of controls designed to allow a user to manipulate and select a color.JComboBox<E> A component that combines a button or editable field and a drop-down list.JComponent The base class for all Swing components except top-level containers.JDesktopPane A container used to create a multiple-document interface or a virtual desktop.JDialog The main class for creating a dialog window.JEditorPane A text component to edit various kinds of content.JFileChooser JFileChooserprovides a simple mechanism for the user to choose a file.JFormattedTextField JFormattedTextFieldextendsJTextFieldadding support for formatting arbitrary values, as well as retrieving a particular object once the user has edited the text.JFormattedTextField.AbstractFormatter Instances ofAbstractFormatterare used byJFormattedTextFieldto handle the conversion both from an Object to a String, and back from a String to an Object.JFormattedTextField.AbstractFormatterFactory Instances ofAbstractFormatterFactoryare used byJFormattedTextFieldto obtain instances ofAbstractFormatterwhich in turn are used to format values.JFrame An extended version ofjava.awt.Framethat adds support for the JFC/Swing component architecture.JInternalFrame A lightweight object that provides many of the features of a native frame, including dragging, closing, becoming an icon, resizing, title display, and support for a menu bar.JInternalFrame.JDesktopIcon This component represents an iconified version of aJInternalFrame.JLabel A display area for a short text string or an image, or both.JLayer<V extends Component> JLayeris a universal decorator for Swing components which enables you to implement various advanced painting effects as well as receive notifications of allAWTEvents generated within its borders.JLayeredPane JLayeredPaneadds depth to a JFC/Swing container, allowing components to overlap each other when needed.JList<E> A component that displays a list of objects and allows the user to select one or more items.JList.DropLocation A subclass ofTransferHandler.DropLocationrepresenting a drop location for aJList.JMenu An implementation of a menu -- a popup window containingJMenuItems that is displayed when the user selects an item on theJMenuBar.JMenuBar An implementation of a menu bar.JMenuItem An implementation of an item in a menu.JOptionPane JOptionPanemakes it easy to pop up a standard dialog box that prompts users for a value or informs them of something.JPanel JPanelis a generic lightweight container.JPasswordField JPasswordFieldis a lightweight component that allows the editing of a single line of text where the view indicates something was typed, but does not show the original characters.JPopupMenu An implementation of a popup menu -- a small window that pops up and displays a series of choices.JPopupMenu.Separator A popup menu-specific separator.JProgressBar A component that visually displays the progress of some task.JRadioButton An implementation of a radio button -- an item that can be selected or deselected, and which displays its state to the user.JRadioButtonMenuItem An implementation of a radio button menu item.JRootPane A lightweight container used behind the scenes byJFrame,JDialog,JWindow,JApplet, andJInternalFrame.JScrollBar An implementation of a scrollbar.JScrollPane Provides a scrollable view of a lightweight component.JSeparator JSeparatorprovides a general purpose component for implementing divider lines - most commonly used as a divider between menu items that breaks them up into logical groupings.JSlider A component that lets the user graphically select a value by sliding a knob within a bounded interval.JSpinner A single line input field that lets the user select a number or an object value from an ordered sequence.JSpinner.DateEditor An editor for aJSpinnerwhose model is aSpinnerDateModel.JSpinner.DefaultEditor A simple base class for more specialized editors that displays a read-only view of the model's current value with aJFormattedTextField.JSpinner.ListEditor An editor for aJSpinnerwhose model is aSpinnerListModel.JSpinner.NumberEditor An editor for aJSpinnerwhose model is aSpinnerNumberModel.JSplitPane JSplitPaneis used to divide two (and only two)Components.JTabbedPane A component that lets the user switch between a group of components by clicking on a tab with a given title and/or icon.JTable TheJTableis used to display and edit regular two-dimensional tables of cells.JTable.DropLocation A subclass ofTransferHandler.DropLocationrepresenting a drop location for aJTable.JTextArea AJTextAreais a multi-line area that displays plain text.JTextField JTextFieldis a lightweight component that allows the editing of a single line of text.JTextPane A text component that can be marked up with attributes that are represented graphically.JToggleButton An implementation of a two-state button.JToggleButton.ToggleButtonModel The ToggleButton modelJToolBar JToolBarprovides a component that is useful for displaying commonly usedActions or controls.JToolBar.Separator A toolbar-specific separator.JToolTip Used to display a "Tip" for a Component.JTree A control that displays a set of hierarchical data as an outline.JTree.DropLocation A subclass ofTransferHandler.DropLocationrepresenting a drop location for aJTree.JTree.DynamicUtilTreeNode DynamicUtilTreeNodecan wrap vectors/hashtables/arrays/strings and create the appropriate children tree nodes as necessary.JTree.EmptySelectionModel EmptySelectionModelis aTreeSelectionModelthat does not allow anything to be selected.JViewport The "viewport" or "porthole" through which you see the underlying information.JWindow AJWindowis a container that can be displayed anywhere on the user's desktop.KeyStroke A KeyStroke represents a key action on the keyboard, or equivalent input device.LayoutFocusTraversalPolicy A SortingFocusTraversalPolicy which sorts Components based on their size, position, and orientation.LayoutStyle LayoutStyleprovides information about how to position components.LookAndFeel LookAndFeel, as the name implies, encapsulates a look and feel.MenuSelectionManager A MenuSelectionManager owns the selection in menu hierarchy.OverlayLayout A layout manager to arrange components over the top of each other.Popup Popups are used to display aComponentto the user, typically on top of all the otherComponents in a particular containment hierarchy.PopupFactory PopupFactory, as the name implies, is used to obtain instances ofPopups.ProgressMonitor A class to monitor the progress of some operation.ProgressMonitorInputStream Monitors the progress of reading from some InputStream.RepaintManager This class manages repaint requests, allowing the number of repaints to be minimized, for example by collapsing multiple requests into a single repaint for members of a component tree.RowFilter<M,I> RowFilteris used to filter out entries from the model so that they are not shown in the view.RowFilter.Entry<M,I> AnEntryobject is passed to instances ofRowFilter, allowing the filter to get the value of the entry's data, and thus to determine whether the entry should be shown.RowSorter<M> RowSorterprovides the basis for sorting and filtering.RowSorter.SortKey SortKey describes the sort order for a particular column.ScrollPaneLayout The layout manager used byJScrollPane.ScrollPaneLayout.UIResource The UI resource version ofScrollPaneLayout.SizeRequirements For the convenience of layout managers, calculates information about the size and position of components.SizeSequence ASizeSequenceobject efficiently maintains an ordered list of sizes and corresponding positions.SortingFocusTraversalPolicy A FocusTraversalPolicy that determines traversal order by sorting the Components of a focus traversal cycle based on a given Comparator.SpinnerDateModel ASpinnerModelfor sequences ofDates.SpinnerListModel A simple implementation ofSpinnerModelwhose values are defined by an array or aList.SpinnerNumberModel ASpinnerModelfor sequences of numbers.Spring An instance of theSpringclass holds three properties that characterize its behavior: the minimum, preferred, and maximum values.SpringLayout ASpringLayoutlays out the children of its associated container according to a set of constraints.SpringLayout.Constraints AConstraintsobject holds the constraints that govern the way a component's size and position change in a container controlled by aSpringLayout.SwingUtilities A collection of utility methods for Swing.SwingWorker<T,V> An abstract class to perform lengthy GUI-interaction tasks in a background thread.Timer Fires one or moreActionEvents at specified intervals.ToolTipManager Manages all theToolTipsin the system.TransferHandler This class is used to handle the transfer of aTransferableto and from Swing components.TransferHandler.DropLocation Represents a location where dropped data should be inserted.TransferHandler.TransferSupport This class encapsulates all relevant details of a clipboard or drag and drop transfer, and also allows for customizing aspects of the drag and drop experience.UIDefaults A table of defaults for Swing components.UIDefaults.LazyInputMap LazyInputMapwill create aInputMapin itscreateValuemethod.UIDefaults.ProxyLazyValue This class provides an implementation ofLazyValuewhich can be used to delay loading of the Class for the instance to be created.UIManager UIManagermanages the current look and feel, the set of available look and feels,PropertyChangeListenersthat are notified when the look and feel changes, look and feel defaults, and convenience methods for obtaining various default values.UIManager.LookAndFeelInfo Provides a little information about an installedLookAndFeelfor the sake of configuring a menu or for initial application set up.ViewportLayout The default layout manager forJViewport. -
Enum Summary Enum Description DropMode Drop modes, used to determine the method by which a component tracks and indicates a drop location during drag and drop.GroupLayout.Alignment Enumeration of the possible waysParallelGroupcan align its children.JTable.PrintMode Printing modes, used in printingJTables.LayoutStyle.ComponentPlacement ComponentPlacementis an enumeration of the possible ways two components can be placed relative to each other.RowFilter.ComparisonType Enumeration of the possible comparison values supported by some of the defaultRowFilters.SortOrder SortOrder is an enumeration of the possible sort orderings.SwingWorker.StateValue Values for thestatebound property. -
Exception Summary Exception Description UnsupportedLookAndFeelException An exception that indicates the requested look & feel management classes are not present on the user's system. -
Annotation Types Summary Annotation Type Description SwingContainer An annotation used to specify some swing-related information for the automatically generatedBeanInfoclasses.