The JavaTM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Trail: Creating a GUI with JFC/Swing
Lesson: Using Swing Components

## The JComponent Class

> With the exception of top-level containers, all Swing components whose names begin with "J" descend from the `JComponent` class. For example, `JPanel`, `JScrollPane`, `JButton`, and `JTable` all inherit from `JComponent`. However, `JFrame` doesn't because it implements a top-level container.

> > Note: A few Swing components aren't top-level containers and yet don't inherit from `JComponent`. The one you're most likely to need is the `Box.Filler` class, which is a non-painting component designed for use with `BoxLayout`. The `Box.Filler` class doesn't inherit from `JComponent` because it is so specialized that it needs no `JComponent` features, and because it is instantiated so often that it should be as small and fast as possible.

> The `JComponent` class extends the `Container` class, which itself extends `Component`. The `Component` class includes everything from providing layout hints to supporting painting and events. The `Container` class has support for adding components to the container and laying them out. This section's API tables summarize the most often used methods of `Component` and `Container`. Information about how to use the methods is scattered throughout this trail.

### JComponent Features

> The `JComponent` class provides the following functionality to its descendants:
> - Tool tips
> - Borders
> - Keyboard-generated actions
> - Application-wide pluggable look and feel
> - Properties
> - Support for layout
> - Support for accessibility
> - Double buffering
> - Methods to increase efficiency
> Tool tips
>   By specifying a string with the `setToolTipText` method, you can provide help to users of a component. When the cursor pauses over the component, the specified string is displayed in a small window that appears near the component. See How to Use Tool Tips for more information.

> Borders
>   The `setBorder` method allows you to specify the border that a component displays around its edges. See How to Use Borders for details.

> Keyboard-generated actions
>   To register a keyboard action, the methods `getActionMap` and `getInputMap` may be used. For example, to bind `aKeyStroke` to `anAction` when `component` has focus, use:

>   >         component.getInputMap().put(aKeyStroke, aCommand);
>   >         component.getActionMap().put(aCommand, anAction);

>   > Version Note: Prior to 1.4, the method `registerKeyboardAction` was used for this same effect. `registerKeyboardAction` is now obsolete.

>   > Note: Some classes provide convenience methods for keyboard actions. For example, `AbstractButton` provides `setMnemonic`, which lets you specify the key that, in combination with a look-and-feel-specific modifier key, causes the button's action to be performed. See How to Use Buttons, Check Boxes, and Radio Buttons for an example of using mnemonics in buttons.

>   The combination of character and modifier keys that the user must press to start an action is represented by a `KeyStroke` object. The resulting action event must be handled by an action listener. Each keyboard action works under exactly one of three conditions: only when the actual component has the focus, only when the component or one of its containers has the focus, or any time that anything in the component's window has the focus.

> Application-wide pluggable look and feel
>   Behind the scenes, each `JComponent` object has a corresponding `ComponentUI` object that performs all the drawing, event handling, size determination, and so on for that `JComponent`. Exactly which `ComponentUI` object is used depends on the current look and feel, which you can set using the `UIManager.setLookAndFeel` method. See How to Set the Look and Feel for details.

> Properties
>   You can associate one or more properties (name/object pairs) with any `JComponent`. For example, a layout manager might use properties to associate a constraints object with each `JComponent` it manages. You put and get properties using the `putClientProperty` and `getClientProperty` methods. For general information about properties, see Using Properties to Manage Program Attributes.

> Support for layout
>   Although the `Component` class provides layout hint methods such as `getPreferredSize` and `getAlignmentX`, it doesn't provide any way to set these layout hints, short of creating a subclass and overriding the methods. To give you another way to set layout hints, the `JComponent` class adds setter methods -- `setPreferredSize`, `setMinimumSize`, `setMaximumSize`, `setAlignmentX`, and `setAlignmentY`. See Layout Management for more information.

> Support for accessibility
>   The `JComponent` class provides API and basic functionality to help assistive technologies such as screen readers get information from Swing components, For more information about accessibility, see How to Support Assistive Technologies.

> Double buffering
>   Double buffering smooths on-screen painting. For details, see Painting.

> Methods to increase efficiency
>   `JComponent` has a few methods that provide more efficient ways to get information than the JDK 1.1 API allowed. The methods include `getX` and `getY`, which you can use instead of `getLocation`; and `getWidth` and `getHeight`, which you can use instead of `getSize`. It also adds one-argument forms of `getBounds`, `getLocation`, and `getSize` for which you specify the object to be modified and returned, letting you avoid unnecessary object creation. These methods have been added to `Component` for Java 2 (JDK 1.2).

### The JComponent API

> The `JComponent` class provides many new methods and inherits many methods from `Component` and `Container`. The following tables summarize the methods we use the most. The table is for reference only. Wherever possible, we provide links to where the API is discussed in more detail.
> - Customizing Component Appearance
> - Setting Component State
> - Handling Events
> - Dealing with Focus
> - Painting Components
> - Dealing with the Containment Hierarchy
> - Laying Out Components
> - Getting Size and Position Information
> - Specifying Absolute Size and Position

> Customizing Component Appearance
> Method | Purpose
> --- | ---
> `void setBorder(Border)` `Border getBorder()` | Set or get the border of the component. See How to Use Borders for details.
> `void setForeground(Color)` `void setBackground(Color)` | Set the foreground or background color for the component. The foreground is generally the color used to draw the text in a component. The background is (not surprisingly) the color of the background areas of the component, assuming that the component is opaque.
> `Color getForeground()` `Color getBackground()` | Get the foreground or background color for the component.
> `void setOpaque(boolean)` `boolean isOpaque()` | Set or get whether the component is opaque. An opaque component fills its background with its background color.
> `void setFont(Font)` `Font getFont()` | Set or get the component's font. If a font has not been set for the component, the font of its parent is returned.
> `FontMetrics getFontMetrics(Font)` | Get the font metrics for the specified font.

> Setting Component State
> Method | Purpose
> --- | ---
> `void setToolTipText(String)` | Set the text to display in a tool tip. See How to Use Tool Tips for more information.
> `void setEnabled(boolean b)` `boolean isEnabled()` | Set or get whether the component is enabled. An enabled component can respond to user input and generate events.
> `void setLocale(Locale l)` `Locale getLocale()` | Set or get the component's locale. If the component does not have a locale, the locale of its parent is returned. See Internationalization for information about locales.
> `static void setDefaultLocale(Locale)` `static Locale getDefaultLocale()` | Get or set the default locale used to initialize each `JComponent`'s locale property upon creation. Introduced in 1.4.
> `void setCursor(Cursor)` `Cursor getCursor()` `boolean isCursorSet()` | Set or get the cursor image to display when the mouse is over the component. The `isCursorSet` method was added to `Component` in 1.4.
> `void setInputVerifier(InputVerifier)` `InputVerifier getInputVerifier()` | Set or get the input verifier for this component. Introduced in 1.3.
> `void setVisible(boolean)` `boolean isVisible()` | Set or get whether the component is visible. Components are initially visible, with the exception of top-level components.

> Handling Events
> (see Event Handling for details)
> Method | Purpose
> --- | ---
> `void setActionMap(ActionMap)` `ActionMap getActionMap()` | Set or get the `ActionMap` used to determine what action to fire for a particular `KeyStroke` binding. Introduced in 1.3.
> `void setInputMap(int, InputMap)` `InputMap getInputMap()` `InputMap getInputMap(int)` | Set or get the `InputMap` used to bind an action to a condition, such as `WHEN_IN_FOCUSED_WINDOW`. Introduced in 1.3.
> `void addMouseWheelListener(MouseWheelListener)` `void removeMouseWheelListener(MouseWheelListener)` | Add or remove a mouse wheel listener to or from the component. Mouse wheel listeners are notified when the component receives mouse wheel events. Introduced in 1.4.
> `void addComponentListener(ComponentListener)` `void removeComponentListener(ComponentListener)` | Add or remove a component listener to or from the component. Component listeners are notified when the listened-to component is hidden, shown, moved, or resized.
> `void addKeyListener(KeyListener)` `void removeKeyListener(KeyListener l)` | Add or remove a key listener to or from the component. Key listeners are notified when the user types at the keyboard and the listened-to component has the keyboard focus.
> `void addMouseListener(MouseListener l)` `void removeMouseListener(MouseListener)` | Add or remove a mouse listener to or from the component. Mouse listeners are notified when the user uses the mouse to interact with the listened-to component.
> `void addMouseMotionListener(MouseMotionListener)` `void removeMouseMotionListener(MouseMotionListener)` | Add or remove a mouse motion listener to or from the component. Mouse motion listeners are notified when the user moves the mouse within the listened-to component's bounds.
> `void addContainerListener(ContainerListener)` `void removeContainerListener(ContainerListener)` | Add or remove a container listener to or from the container. Container listeners are notified when a component is added to or removed from the listened-to container.
> `void setTransferHandler(TransferHandler)` `TransferHandler getTransferHandler()` | Set or remove the `transferHandler` property. The `TransferHandler` supports exchanging data via cut, copy, or paste to/from a clipboard as well a drag and drop. See Drag and Drop for more details. Introduced in 1.4.
> `boolean contains(int, int)` `boolean contains(Point p)` | Determine whether the specified point is within the component. The argument should be specified in terms of the component's coordinate system. The two `int` arguments specify x and y coordinates, respectively.
> `Component getComponentAt(int, int)` | Return the component that contains the specified x, y position. The top-most child component is returned in the case where components overlap. This is determined by finding the component closest to the index 0 that claims to contain the given point via `Component.contains()`.

> Dealing with Focus
> (see the Focus Specification for details)
> Method | Purpose
> --- | ---
> `void addFocusListener(FocusListener)` `void removeFocusListener(FocusListener)` | Add or remove a focus listener to or from the component. Focus listeners are notified when the listened-to component gains or loses keyboard focus.
> `Component getNextFocusableComponent()` `void setNextFocusableComponent(Component)` | Version Note: These methods have been deprecated in 1.4. They have been replaced by FocusTraversalPolicy. Set or get the next focusable component. `null` indicates that the focus manager should choose the next focusable component automatically.
> `setFocusable(boolean)` `boolean isFocusable()` | Set or get whether the component can receive focus. Introduced in 1.4.
> `void requestFocus()` `boolean hasFocus()` | Request that the component get the keyboard focus, or detect whether it has the focus.
> `boolean requestFocusInWindow()` | Request that this component get the input focus, if this component's top-level ancestor is already the focused window. Introduced in 1.4.
> `void setVerifyInputWhenFocusTarget(boolean)` `boolean getVerifyInputWhenFocusTarget()` | Set or get whether the input verifier for the current focus owner will be called before the component requests focus. Introduced in 1.3.
> `void setFocusTraversalKeys(int, Set)` `Set getFocusTraversalKeys(int)` `void areFocusTraversalKeysSet(int)` | Set or get the focus traversal keys for a given traversal operation for this container. Introduced in 1.4.
> `Container getFocusCycleRootAncestor()` | Get the container that is the focus cycle root of this component's focus traversal cycle. Introduced in 1.4.
> `void setFocusTraversalKeysEnabled(boolean)` `boolean getFocusTraversalKeysEnabled()` | Set or get whether the focus traversal keys are enabled for this component. Introduced in 1.4.
> `void setFocusTraversalPolicy(FocusTraversalPolicy)` `FocusTraversalPolicy getFocusTraversalPolicy()` `boolean isFocusTraversalPolicySet()` | Set or get the focus traversal policy that manages the keyboard traversal of this container's children, if this container is a focus cycle root. Introduced in 1.4.
> `boolean setFocusCycleRoot(boolean)` `void isFocusCycleRoot(Container)` | Set or get whether this container is the root of a focus traversal cycle. Introduced in 1.4.
> `boolean isFocusOwner()` | Get whether this component is the focus owner. Introduced in 1.4.
> `void transferFocusBackward()` `void transferFocusDownCycle()` `void transferFocusUpCycle()` | Transfer the focus to the previous component, or down or up one focus traversal cycle, depending upon the direction specified by the method name. Introduced in 1.4.

> Painting Components
> (see Painting for details)
> Method | Purpose
> --- | ---
> `void repaint()` `void repaint(int, int, int, int)` | Request that all or part of the component be repainted. The four `int` arguments specify the bounds (x, y, width, height, in that order) of the rectangle to be painted.
> `void repaint(Rectangle)` | Request that the specified area within the component be repainted.
> `void revalidate()` | Request that the component and its affected containers be laid out again. You shouldn't generally need to invoke this method unless you explicitly change a component's size/alignment hints after it's visible, change a containment hierarchy after it's visible, or perhaps change the data in a component's model directly (without going through the component's API). You might need to invoke `repaint` after `revalidate`.
> `void paintComponent(Graphics)` | Paint the component. Override this method to implement painting for custom components.
> `void printBorder(Graphics)` `void printChildren(Graphics)` `void printComponent(Graphics)` | Prints the component's border, the component's children, or the component itself. These are implemented to invoke `paintBorder`, `paintChildren`, or `paintComponent`, respectively, on the component. Override if you wish to print any of these items differently than otherwise painted. Introduced in 1.3.

> Dealing with the Containment Hierarchy
> (see Swing Components and the Containment Hierarchy for more information)
> Method | Purpose
> --- | ---
> `Component add(Component)` `Component add(Component, int)` `void add(Component, Object)` | Add the specified component to the container. The one-argument version of this method adds the component to the end of the container. When present, the `int` argument indicates the new component's position within the container. When present, the `Object` argument provides layout constraints to the current layout manager.
> `void remove(int)` `void remove(Component comp)` `void removeAll()` | Remove one of or all of the components from the container. When present, the `int` argument indicates the position within the container of the component to remove.
> `JRootPane getRootPane()` | Get the root pane ancestor for the component.
> `Container getParent()` | Get the component's parent.
> `int getComponentCount()` | Get the number of components in the container.
> `Component getComponent(int)` `Component[] getComponents()` | Get the one of or all of the components in the container. The `int` argument indicates the position of the component to get.

> Laying Out Components
> (see Laying Out Components Within a Container for more information)
> Method | Purpose
> --- | ---
> `void applyComponentOrientation(ComponentOrientation)` | Set the `ComponentOrientation` property of this container and all the components contained within it. Introduced in 1.4.
> `void setPreferredSize(Dimension)` `void setMaximumSize(Dimension)` `void setMinimumSize(Dimension)` | Set the component's preferred, maximum, or minimum size, measured in pixels. The preferred size indicates the best size for the component. The component should be no larger than its maximum size and no smaller than its minimum size. Be aware that these are hints only and might be ignored by certain layout managers.
> `Dimension getPreferredSize()` `Dimension getMaximumSize()` `Dimension getMinimumSize()` | Get the preferred, maximum, or minimum size of the component, measured in pixels. For non-`JComponent` subclasses, which don't have the corresponding setter methods, you can set a component's preferred, maximum, or minimum size by creating a subclass and overriding these methods.
> `void setAlignmentX(float)` `void setAlignmentY(float)` | Set the alignment along the x- or y- axis. These values indicate how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, and 0.5 is centered, and so on. Be aware that these are hints only and might be ignored by certain layout managers.
> `float getAlignmentX()` `float getAlignmentY()` | Get the alignment of the component along the x- or y- axis. For non-`JComponent` subclasses, which don't have the corresponding setter methods, you can set a component's alignment by creating a subclass and overriding these methods.
> `void setLayout(LayoutManager)` `LayoutManager getLayout()` | Set or get the component's layout manager. The layout manager is responsible for sizing and positioning the components within a container.

> Getting Size and Position Information
> Method | Purpose
> --- | ---
> `int getWidth()` `int getHeight()` | Get the current width or height of the component measured in pixels.
> `Dimension getSize()` `Dimension getSize(Dimension)` | Get the component's current size measured in pixels. When using the one-argument version of this method, the caller is responsible for creating the `Dimension` instance in which the result is returned.
> `int getX()` `int getY()` | Get the current x or y coordinate of the component's origin relative to the parent's upper left corner measured in pixels.
> `Rectangle getBounds()` `Rectangle getBounds(Rectangle)` | Get the bounds of the component measured in pixels. The bounds specify the component's width, height, and origin relative to its parent. When using the one-argument version of this method, the caller is responsible for creating the `Rectangle` instance in which the result is returned.
> `Point getLocation()` `Point getLocation(Point)` `Point getLocationOnScreen()` | Gets the current location of the component relative to the parent's upper left corner measured in pixels. When using the one-argument version of `getLocation` method, the caller is responsible for creating the `Point` instance in which the result is returned. The `getLocationOnScreen` method returns the position relative to the upper left corner of the screen.
> `Insets getInsets()` | Get the insets of the component.

> Specifying Absolute Size and Position
> (see Doing Without a Layout Manager (Absolute Positioning) for more information)
> Method | Purpose
> --- | ---
> `void setLocation(int, int)` `void setLocation(Point)` | Set the location of the component, in pixels, relative to the parent's upper left corner. The two `int` arguments specify x and y, in that order. Use these methods to position a component when you aren't using layout manager.
> `void setSize(int, int)` `void setSize(Dimension)` | Set the size of the component measured in pixels. The two `int` arguments specify width and height, in that order. Use these methods to size a component when you aren't using layout manager.
> `void setBounds(int, int, int, int)` `void setBounds(Rectangle)` | Set the size and location relative to the parent's upper left corner, in pixels, of the component. The four `int` arguments specify x, y, width, and height, in that order. Use these methods to position and size a component when you aren't using layout manager.

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.