The JavaTM Tutorial
Previous Page Lesson Contents Next Page 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(in the API reference documentation) 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(in the Creating a GUI with JFC/Swing trail). 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(in the API reference documentation) class, which itself extends Component(in the API reference documentation). 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
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(in the Creating a GUI with JFC/Swing trail) for details.

Keyboard-generated actions
Using the registerKeyboardAction method, you can enable the user to use the keyboard, instead of the mouse, to operate the GUI.

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(in the API reference documentation) object. The resulting action event must be handled by an action listener(in the Creating a GUI with JFC/Swing trail). 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(in the Creating a GUI with JFC/Swing trail) 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(in the Creating a GUI with JFC/Swing trail).

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(in the Creating a GUI with JFC/Swing trail) 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(in the Creating a GUI with JFC/Swing trail).

Double buffering
Double buffering smooths on-screen painting. For details, see Painting(in the Creating a GUI with JFC/Swing trail).

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
Method Purpose
void setBorder(Border)
Border getBorder()

(in JComponent)
Set or get the border of the component. See How to Use Borders(in the Creating a GUI with JFC/Swing trail) for details.
void setForeground(Color)
Color getForeground()
void setBackground(Color)
Color getBackground()

(in java.awt.Component)
Set or get 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.
void setOpaque(boolean)
(in JComponent)
Set whether the component is opaque. An opaque component fills its background with its background color.
boolean isOpaque
(in JComponent)
Get whether the component is opaque. This method (but not setOpaque) was added to Component in 1.2.
void setFont(Font)
Font getFont()

(in java.awt.Component)
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)
(in java.awt.Component)
Get the font metrics for the specified font.

Setting Component State
Method Purpose
void setToolTipText(String)
(in JComponent)
Set the text to display in a tool tip. See How to Use Tool Tips for more information.
void setEnabled(boolean b)
boolean isEnabled()

(in java.awt.Component)
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()

(in java.awt.Component)
Set or get the component's locale. If the component does not have a locale, the locale of its parent is returned. See Internationalization(in the Creating a GUI with JFC/Swing trail) for information about locales.
void setCursor(Cursor)
Cursor getCursor()

(in java.awt.Component)
Set or get the cursor image to display when the mouse is over the component.
void setVisible(boolean)
boolean isVisible()

(in java.awt.Component)
Set or get whether the component is visible. Components are initially visible, with the exception of top-level components.

Handling Events
(see
Event Handling(in the Creating a GUI with JFC/Swing trail) for details)
Method Purpose
void addComponentListener(ComponentListener)
void removeComponentListener(ComponentListener)

(in java.awt.Component)
Add or remove a component listener(in the Creating a GUI with JFC/Swing trail) 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)

(in java.awt.Component)
Add or remove a key listener(in the Creating a GUI with JFC/Swing trail) 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.
addMouseListener(MouseListener l)
void removeMouseListener(MouseListener)

(in java.awt.Component)
Add or remove a mouse listener(in the Creating a GUI with JFC/Swing trail) 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)

(in java.awt.Component)
Add or remove a mouse motion listener(in the Creating a GUI with JFC/Swing trail) 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)

(in java.awt.Container)
Add or remove a container listener(in the Creating a GUI with JFC/Swing trail) to or from the container. Container listeners are notified when a component is added to or removed from the listened-to container.
void addFocusListener(FocusListener)
void removeFocusListener(FocusListener)

(in java.awt.Component)
Add or remove a focus listener(in the Creating a GUI with JFC/Swing trail) to or from the component. Focus listeners are notified when the listened-to component gains or loses keyboard focus.
Component getNextFocusableComponent()
void setNextFocusableComponent(Component)

(in JComponent)
Set or get the next focusable component. null indicates that the focus manager should choose the next focusable component automatically.
void requestFocus()
boolean hasFocus()

(in java.awt.Component)
Request that the component get the keyboard focus, or detect whether it has the focus.
boolean contains(int, int)
boolean contains(Point p)

(in java.awt.Component)
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)
(in java.awt.Container)
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().

Painting Components
(see
Painting(in the Creating a GUI with JFC/Swing trail) for details)
Method Purpose
void repaint()
void repaint(int, int, int, int)

(in java.awt.Component)
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)
(in JComponent)
Request that the specified area within the component be repainted.
void revalidate()
(in JComponent)
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)
(in JComponent)
Paint the component. Override this method to implement painting for custom components.

Dealing with the Containment Hierarchy
(see
Swing Components and the Containment Hierarchy(in the Creating a GUI with JFC/Swing trail) for more information)
Method Purpose
Component add(Component)
Component add(Component, int)
void add(Component, Object)

(in java.awt.Container)
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()

(in java.awt.Container)
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()
(in JComponent)
Get the root pane ancestor for the component.
Container getParent()
(in java.awt.Component)
Get the component's parent.
int getComponentCount()
(in java.awt.Container)
Get the number of components in the container.
Component getComponent(int)
Component[] getComponents()

(in java.awt.Container)
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(in the Creating a GUI with JFC/Swing trail) for more information)
Method Purpose
void setPreferredSize(Dimension)
void setMaximumSize(Dimension)
void setMinimumSize(Dimension)

(in JComponent)
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()

(in java.awt.Component)
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)

(in JComponent)
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()

(in java.awt.Component)
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()

(in java.awt.Container)
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()

(in java.awt.Component)
Get the current width or height of the component measured in pixels.
Dimension getSize()
Dimension getSize(Dimension)

(in java.awt.Component)
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()

(in java.awt.Component)
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)

(in java.awt.Component)
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()

(in java.awt.Component)
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()
(in java.awt.Container)
Get the insets of the component.

Specifying Absolute Size and Position
(see
Doing Without a Layout Manager (Absolute Positioning)(in the Creating a GUI with JFC/Swing trail) for more information)
Method Purpose
void setLocation(int, int)
void setLocation(Point)

(in java.awt.Component)
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)

(in java.awt.Component)
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)

(in java.awt.Component)
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.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form