The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.
SeeDev.java for updated tutorials taking advantage of the latest releases.
SeeJava Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
SeeJDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.
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
andJDialog
don't because they implement top-level containers.
TheJComponent
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'sAPI tables summarize the most often used methods ofComponent
andContainer
, as well as ofJComponent
.
TheJComponent
class provides the following functionality to its descendants:
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. SeeHow to Use Tool Tips for more information.setBorder
method allows you to specify the border that a component displays around its edges. To paint the inside of a component, override thepaintComponent
method. SeeHow to Use Borders andPerforming Custom Painting for details.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. SeeHow to Set the Look and Feel for details.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, seeProperties.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 setMinimumSize
,setMaximumSize
,setAlignmentX
, andsetAlignmentY
. SeeLaying Out Components Within a Container for more information.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, seeHow to Support Assistive Technologies.JComponent
class provides API to set a component's transfer handler, which is the basis for Swing's drag and drop support. SeeIntroduction to DnD for details.TheJComponent
class provides many new methods and inherits many methods fromComponent
andContainer
. The following tables summarize the methods we use the most.
Method | Purpose |
---|---|
void setBorder(Border) Border getBorder() | Set or get the border of the component. SeeHow 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. |
void setCursor(Cursor) Cursor getCursor() | Set or get the cursor displayed over the component and all components it contains (except for children that have their own cursor set). Example:aPanel.setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR)); |
Method | Purpose |
---|---|
void setComponentPopupMenu(JPopupMenu) | Sets theJPopupMenu for thisJComponent . The UI is responsible for registering bindings and adding the necessary listeners such that theJPopupMenu will be shown at the appropriate time. When theJPopupMenu is shown depends upon the look and feel: some may show it on a mouse event, some may enable a key binding.If popup is null, andgetInheritsPopupMenu returnstrue , thengetComponentPopupMenu will be delegated to the parent. This provides for a way to make all child components inherit thepopupmenu of the parent. |
void setTransferHandler(TransferHandler) TransferHandler getTransferHandler() | Set or remove thetransferHandler property. TheTransferHandler supports exchanging data via cut, copy, or paste to/from a clipboard as well a drag and drop. SeeIntroduction to DnD for more details. |
void setToolTipText(String) | Set the text to display in a tool tip. SeeHow to Use Tool Tips for more information. |
void setName(String) String getName() | Set or get the name of the component. This can be useful when you need to associate text with a component that does not display text. |
boolean isShowing() | Determine whether the component is showing on screen. This means that the component must be visible, and it must be in a container that is visible and showing. |
void setEnabled(boolean) boolean isEnabled() | Set or get whether the component is enabled. An enabled component can respond to user input and generate events. |
void setVisible(boolean) boolean isVisible() | Set or get whether the component is visible. Components are initially visible, with the exception of top-level components. |
Method | Purpose |
---|---|
void addHierarchyListener(hierarchyListener l) void removeHierarchyListener(hierarchyListener l) | Adds or removes the specified hierarchy listener to receive hierarchy changed events from this component when the hierarchy to which this container belongs changes. If listener l is null, no exception is thrown and no action is performed. |
void addMouseListener(MouseListener) void removeMouseListener(MouseListener) | Add or remove amouse 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 amouse 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 addKeyListener(KeyListener) void removeKeyListener(KeyListener) | Add or remove akey 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 addComponentListener(ComponentListener) void removeComponentListener(ComponentListener) | Add or remove acomponent listener to or from the component. Component listeners are notified when the listened-to component is hidden, shown, moved, or resized. |
boolean contains(int, int) boolean contains(Point) | Determine whether the specified point is within the component. The argument should be specified in terms of the component's coordinate system. The twoint arguments specifyx andy coordinates, respectively. |
Component getComponentAt(int, int) Component getComponentAt(Point) | Return the component that contains the specifiedx, 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 viaComponent.contains() . |
Component setComponentZOrder(component comp, int index) | Moves the specified component to the specified z-order index in the container. If the component is a child of some other container, it is removed from that container before being added to this container. The important difference between this method and java.awt.Container.add(Component, int) is that this method doesn't callremoveNotify on the component while removing it from its previous container unless necessary and when allowed by the underlying native windowing system. This way, if the component has the keyboard focus, it maintains the focus when moved to the new position.Note: The z-order determines the order that components are painted. The component with the highest z-order paints first and the component with the lowest z-order paints last. Where components overlap, the component with the lower z-order paints over the component with the higher z-order. |
Component getComponentZOrder(component comp) | Returns the z-order index of the component inside the container. The higher a component is in the z-order hierarchy, the lower its index. The component with the lowest z-order index is painted last, above all other child components. |
Method | Purpose |
---|---|
void repaint() void repaint(int, int, int, int) | Request that all or part of the component be repainted. The fourint 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 should not generally need to invoke this method unless you explicitly change a component's size/alignment hints after it's visible or change a containment hierarchy after it is visible. Always invokerepaint afterrevalidate . |
void paintComponent(Graphics) | Paint the component. Override this method to implement painting for custom components. |
Method | Purpose |
---|---|
Component add(Component) Component add(Component, int) void add(Component, Object) | Add the specified component to this container. The one-argument version of this method adds the component to the end of the container. When present, theint 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) void removeAll() | Remove one of or all of the components from this container. When present, theint argument indicates the position within the container of the component to remove. |
JRootPane getRootPane() | Get the root pane that contains the component. |
Container getTopLevelAncestor() | Get the topmost container for the component aWindow ,Applet , or null if the component has not been added to any container. |
Container getParent() | Get the component's immediate container. |
int getComponentCount() | Get the number of components in this container. |
Component getComponent(int) Component[] getComponents() | Get the one of or all of the components in this container. Theint argument indicates the position of the component to get. |
Component getComponentZOrder(int) Component[] getComponentZOrder() | Returns the z-order index of the component inside the container. The higher a component is in the z-order hierarchy, the lower its index. The component with the lowest z-order index is painted last, above all other child components. |
Method | Purpose |
---|---|
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. Many JComponent classes have setter and getter methods. For those non-JComponent subclasses, which do not 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 thex- ory- 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 thex- ory- axis. For non-JComponent subclasses, which do not 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. |
void applyComponentOrientation(ComponentOrientation)void setComponentOrientation(ComponentOrientation) | Set theComponentOrientation property of this container and all the components contained within it. SeeSetting the Container's Orientation for more 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 theDimension instance in which the result is returned. |
int getX() int getY() | Get the currentx 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 theRectangle instance in which the result is returned. |
Point getLocation() Point getLocation(Point) | Gets the current location of the component relative to the parent's upper left corner measured in pixels. When using the one-argument version ofgetLocation method, the caller is responsible for creating thePoint instance in which the result is returned. |
Point getLocationOnScreen() | Returns the position relative to the upper left corner of the screen. |
Insets getInsets() | Get the size of the component's border. |
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 twoint arguments specifyx andy, in that order. Use these methods to position a component when you are not using a layout manager. |
void setSize(int, int) void setSize(Dimension) | Set the size of the component measured in pixels. The twoint arguments specify width and height, in that order. Use these methods to size a component when you are not using a 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 fourint arguments specifyx,y, width, and height, in that order. Use these methods to position and size a component when you are not using a layout manager. |
About Oracle |Contact Us |Legal Notices |Terms of Use |Your Privacy Rights
Copyright © 1995, 2024 Oracle and/or its affiliates. All rights reserved.