Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
With the exception of top-level containers, all Swing components whose names begin with "J" descend from theJComponent
class. For example,JPanel
,JScrollPane
,JButton
, andJTable
all inherit fromJComponent
. 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 fromJComponent
. The one you're most likely to need is theBox.Filler
class, which is a non-painting component designed for use withBoxLayout
. TheBox.Filler
class doesn't inherit fromJComponent
because it is so specialized that it needs noJComponent
features, and because it is instantiated so often that it should be as small and fast as possible.The
JComponent
class extends theContainer
class, which itself extendsComponent
. TheComponent
class includes everything from providing layout hints to supporting painting and events. TheContainer
class has support for adding components to the container and laying them out. This section's API tables summarize the most often used methods ofComponent
andContainer
. Information about how to use the methods is scattered throughout this trail.
TheJComponent
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
- Using the
registerKeyboardAction
method, you can enable the user to use the keyboard, instead of the mouse, to operate the GUI.The combination of character and modifier keys that the user must press to start an action is represented by a
Note: Some classes provide convenience methods for keyboard actions. For example,AbstractButton
providessetMnemonic
, 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.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 correspondingComponentUI
object that performs all the drawing, event handling, size determination, and so on for thatJComponent
. Exactly whichComponentUI
object is used depends on the current look and feel, which you can set using theUIManager.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 eachJComponent
it manages. You put and get properties using theputClientProperty
andgetClientProperty
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 asgetPreferredSize
andgetAlignmentX
, 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, theJComponent
class adds setter methods --setPreferredSize
,setMinimumSize
,setMaximumSize
,setAlignmentX
, andsetAlignmentY
. 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 includegetX
andgetY
, which you can use instead ofgetLocation
; andgetWidth
andgetHeight
, which you can use instead ofgetSize
. It also adds one-argument forms ofgetBounds
,getLocation
, andgetSize
for which you specify the object to be modified and returned, letting you avoid unnecessary object creation. These methods have been added toComponent
for Java 2 (JDK 1.2).
TheJComponent
class provides many new methods and inherits many methods fromComponent
andContainer
. 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
- 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()
(inJComponent
)Set or get the border of the component. See How to Use Borders for details. void setForeground(Color)
Color getForeground()
void setBackground(Color)
Color getBackground()
(injava.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)
(inJComponent
)Set whether the component is opaque. An opaque component fills its background with its background color. boolean isOpaque
(inJComponent
)Get whether the component is opaque. This method (but not setOpaque
) was added toComponent
in 1.2.void setFont(Font)
Font getFont()
(injava.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)
(injava.awt.Component
)Get the font metrics for the specified font.
Setting Component State Method Purpose void setToolTipText(String)
(inJComponent
)Set the text to display in a tool tip. See How to Use Tool Tips for more information. void setEnabled(boolean b)
boolean isEnabled()
(injava.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()
(injava.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 for information about locales. void setCursor(Cursor)
Cursor getCursor()
(injava.awt.Component
)Set or get the cursor image to display when the mouse is over the component. void setVisible(boolean)
boolean isVisible()
(injava.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 for details)Method Purpose void addComponentListener(ComponentListener)
void removeComponentListener(ComponentListener)
(injava.awt.Component
)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)
(injava.awt.Component
)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. addMouseListener(MouseListener l)
void removeMouseListener(MouseListener)
(injava.awt.Component
)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)
(injava.awt.Component
)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)
(injava.awt.Container
)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 addFocusListener(FocusListener)
void removeFocusListener(FocusListener)
(injava.awt.Component
)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)
(inJComponent
)Set or get the next focusable component. null
indicates that the focus manager should choose the next focusable component automatically.void requestFocus()
boolean hasFocus()
(injava.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)
(injava.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)
(injava.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 for details)Method Purpose void repaint()
void repaint(int, int, int, int)
(injava.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)
(inJComponent
)Request that the specified area within the component be repainted. void revalidate()
(inJComponent
)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
afterrevalidate
.void paintComponent(Graphics)
(inJComponent
)Paint the component. Override this method to implement painting for custom components.
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)
(injava.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, theObject
argument provides layout constraints to the current layout manager.void remove(int)
void remove(Component comp)
void removeAll()
(injava.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()
(inJComponent
)Get the root pane ancestor for the component. Container getParent()
(injava.awt.Component
)Get the component's parent. int getComponentCount()
(injava.awt.Container
)Get the number of components in the container. Component getComponent(int)
Component[] getComponents()
(injava.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 for more information)Method Purpose void setPreferredSize(Dimension)
void setMaximumSize(Dimension)
void setMinimumSize(Dimension)
(inJComponent
)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()
(injava.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)
(inJComponent
)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()
(injava.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()
(injava.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()
(injava.awt.Component
)Get the current width or height of the component measured in pixels. Dimension getSize()
Dimension getSize(Dimension)
(injava.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()
(injava.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)
(injava.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()
(injava.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 thePoint
instance in which the result is returned. ThegetLocationOnScreen
method returns the position relative to the upper left corner of the screen.Insets getInsets()
(injava.awt.Container
)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)
(injava.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)
(injava.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)
(injava.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.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |