Documentation

The Java™ Tutorials
Hide TOC
The JComponent ClassJComponent
Trail: Creating a GUI With Swing
Lesson: Using Swing Components

The JComponent ClassJComponent

With the exception of top-level containers, all Swing components whose names begin with "J" descend from the JComponent class. 除了顶级容器之外,所有名称以“J”开头的Swing组件都是从JComponent类派生的。For example, JPanel, JScrollPane, JButton, and JTable all inherit from JComponent. However, JFrame and JDialog don't because they implement top-level containers.例如,JPanelJScrollPaneJButtonJTable都从JComponent继承。然而,JFrameJDialog没有,因为它们实现了顶级容器。

The JComponent class extends the Container class, which itself extends Component. JComponent类扩展Container类,而Container类本身扩展了Component类。The Component class includes everything from providing layout hints to supporting painting and events. Component类包括从提供布局提示到支持绘制和事件的所有内容。The Container class has support for adding components to the container and laying them out. Container类支持向容器中添加组件并对其进行布局。This section's API tables summarize the most often used methods of Component and Container, as well as of JComponent. 本节的API表总结了ComponentContainer以及JComponent最常用的方法。

JComponent Features功能

The JComponent class provides the following functionality to its descendants:JComponent类为其后代提供了以下功能:

Tool tips工具提示
By specifying a string with the setToolTipText method, you can provide help to users of a component. 通过使用setToolTipText方法指定字符串,可以为组件的用户提供帮助。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.有关详细信息,请参阅如何使用工具提示
Painting and borders绘画和边框
The setBorder method allows you to specify the border that a component displays around its edges. setBorder方法允许您指定零部件在其边缘周围显示的边界。To paint the inside of a component, override the paintComponent method. 要绘制组件的内部,请重写paintComponent方法。See How to Use Borders and Performing Custom Painting for details.有关详细信息,请参阅如何使用边框执行自定义绘制
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. 在幕后,每个JComponent对象都有一个对应的ComponentUI对象,该对象执行该jComponen的所有绘图、事件处理、大小确定等操作。Exactly which ComponentUI object is used depends on the current look and feel, which you can set using the UIManager.setLookAndFeel method. 具体使用哪个ComponentUI对象取决于当前的外观,您可以使用UIManager.setLookAndFeel方法设置当前的外观。See How to Set the Look and Feel for details.有关详细信息,请参阅如何设置外观
Custom properties自定义属性
You can associate one or more properties (name/object pairs) with any JComponent. 您可以将一个或多个属性(名称/对象对)与任何JComponent关联。For example, a layout manager might use properties to associate a constraints object with each JComponent it manages. 例如,布局管理器可能使用属性将约束对象与其管理的每个JComponent关联起来。You put and get properties using the putClientProperty and getClientProperty methods. 使用putClientPropertygetClientProperty方法放置和获取属性。For general information about properties, see Properties.有关属性的常规信息,请参阅属性
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. 尽管Component类提供了布局提示方法,如getPreferredSizegetAlignmentX,但除了创建子类和重写这些方法之外,它不提供任何设置这些布局提示的方法。To give you another way to set layout hints, the JComponent class adds setter methods — setMinimumSize, setMaximumSize, setAlignmentX, and setAlignmentY. 为了提供另一种设置布局提示的方法,JComponent类添加了setter方法—setMinimumSizesetMaximumSizesetAlignmentXsetAlignmentYSee Laying Out Components Within a Container 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.JComponent类提供了API和基本功能,以帮助辅助技术(如屏幕阅读器)从Swing组件获取信息。有关可访问性的更多信息,请参阅如何支持辅助技术
Support for drag and drop支持拖放
The JComponent class provides API to set a component's transfer handler, which is the basis for Swing's drag and drop support. JComponent类提供了设置组件传输处理程序的API,这是Swing拖放支持的基础。See Introduction to DnD for details.详见DnD简介
Double buffering双缓冲
Double buffering smooths on-screen painting. 双缓冲平滑屏幕绘制。For details, see Performing Custom Painting.有关详细信息,请参阅执行自定义绘制
Key bindings键绑定
This feature makes components react when the user presses a key on the keyboard. 此功能使组件在用户按下键盘上的键时做出反应。For example, in many look and feels when a button has the focus, typing the Space key is equivalent to a mouse click on the button. 例如,在许多外观中,当按钮具有焦点时,键入空格键相当于鼠标单击按钮。The look and feel automatically sets up the bindings between pressing and releasing the Space key and the resulting effects on the button. 外观会自动设置按下和释放空格键之间的绑定,以及按钮上产生的效果。For more information about key bindings, see How to Use Key Bindings.有关键绑定的详细信息,请参阅如何使用键绑定

The JComponent API

The JComponent class provides many new methods and inherits many methods from Component and Container. JComponent类提供了许多新方法,并从ComponentContainer继承了许多方法。The following tables summarize the methods we use the most.下表总结了我们最常用的方法。

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.如果尚未为组件设置字体,则返回其父级的字体。
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));
Setting and Getting Component State设置和获取组件状态
Method方法 Purpose目的
void setComponentPopupMenu(JPopupMenu) Sets the JPopupMenu for this JComponent. 设置此JComponentJPopupMenuThe UI is responsible for registering bindings and adding the necessary listeners such that the JPopupMenu will be shown at the appropriate time. UI负责注册绑定并添加必要的监听器,以便在适当的时间显示JPopupMenuWhen the JPopupMenu is shown depends upon the look and feel: some may show it on a mouse event, some may enable a key binding.何时显示JPopupMenu取决于外观:有些可能在鼠标事件上显示,有些可能启用键绑定。

If popup is null, and getInheritsPopupMenu returns true, then getComponentPopupMenu will be delegated to the parent. 如果popup为空,并且getInheritsPopupMenu返回true,则getComponentPopupMenu将委托给父级。This provides for a way to make all child components inherit the popupmenu of the parent.这提供了一种使所有子组件继承父组件的popupmenu(弹出菜单)的方法。
void setTransferHandler(TransferHandler)
TransferHandler getTransferHandler()
Set or remove the transferHandler property. 设置或删除transferHandler属性。The TransferHandler supports exchanging data via cut, copy, or paste to/from a clipboard as well a drag and drop. TransferHandler支持通过剪切、复制或粘贴到剪贴板以及拖放来交换数据。See Introduction to DnD for more details.有关详细信息,请参阅DnD简介
void setToolTipText(String) Set the text to display in a tool tip. 设置要在工具提示中显示的文本。See How 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.组件最初可见,但顶级组件除外。
Handling Events处理事件
(see Writing Event Listeners for details)(有关详细信息,请参阅编写事件侦听器。)
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.如果侦听器l为空,则不会引发异常,也不会执行任何操作。
void addMouseListener(MouseListener)
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 addKeyListener(KeyListener)
void removeKeyListener(KeyListener)
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 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.当被侦听的组件被隐藏、显示、移动或调整大小时,将通知组件侦听器。
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 two int arguments specify x and y coordinates, respectively.两个int参数分别指定xy坐标。
Component getComponentAt(int, int)
Component getComponentAt(Point)
Return the component that contains the specified x, y position. 返回包含指定x, y位置的组件。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().这是通过查找最接近索引0的组件来确定的,该组件通过Component.contains()声明包含给定点。
Component setComponentZOrder(component comp, int index)
Moves the specified component to the specified z-order index in the container.将指定的组件移动到容器中指定的z顺序索引。

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 call removeNotify on the component while removing it from its previous container unless necessary and when allowed by the underlying native windowing system. 此方法与java.awt.Container.add(Component, int)之间的重要区别在于,除非必要且底层本机窗口系统允许,否则此方法在将组件从以前的容器中移除时不会对组件调用removeNotifyThis 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. z顺序确定零部件的绘制顺序。The component with the highest z-order paints first and the component with the lowest z-order paints last. z阶最高的组分首先涂漆,z阶最低的组分最后涂漆。Where components overlap, the component with the lower z-order paints over the component with the higher z-order.在组件重叠的地方,z阶较低的组件覆盖z阶较高的组件。

Component getComponentZOrder(component comp)
Returns the z-order index of the component inside the container. 返回容器内组件的z顺序索引。The higher a component is in the z-order hierarchy, the lower its index. 组件在z阶层次结构中的位置越高,其索引越低。The component with the lowest z-order index is painted last, above all other child components.z阶索引最低的组件最后绘制,高于所有其他子组件。
Painting Components涂色组件
(see Performing Custom 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.四个int参数指定要绘制的矩形的边界(依次为xywidthheight,)。
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 invoke repaint after revalidate.始终在revalidate后调用repaint
void paintComponent(Graphics) Paint the component. 绘制组件。Override this method to implement painting for custom components.重写此方法以实现自定义零部件的绘制。
Dealing with the Containment Hierarchy处理包含层次结构
(see Using Top-Level Containers for more information)(有关详细信息,请参阅使用顶级容器。)
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, the int argument indicates the new component's position within the container. 如果存在,int参数表示新组件在容器中的位置。When present, the Object argument provides layout constraints to the current layout manager.如果存在,Object参数将为当前布局管理器提供布局约束。
void remove(int)
void remove(Component)
void removeAll()
Remove one of or all of the components from this container. 从此容器中移除一个或所有组件。When present, the int argument indicates the position within the container of the component to remove.如果存在,int参数表示要删除的组件在容器中的位置。
JRootPane getRootPane() Get the root pane that contains the component.获取包含组件的根窗格。
Container getTopLevelAncestor() Get the topmost container for the component — a Window, Applet, or null if the component has not been added to any container.获取组件—WindowApplet或空(如果组件未添加到任何容器中)。
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. 获取此容器中的一个或所有组件。The int argument indicates the position of the component to get.int参数指示要获取的组件的位置。
Component getComponentZOrder(int)
Component[] getComponentZOrder()
Returns the z-order index of the component inside the container. 返回容器内组件的z顺序索引。The higher a component is in the z-order hierarchy, the lower its index. 组件在z阶层次结构中的位置越高,其索引越低。The component with the lowest z-order index is painted last, above all other child components.z阶索引最低的组件最后绘制,高于所有其他子组件。
Laying Out Components组件布局
(see Laying Out Components Within a Container for more information)(有关详细信息,请参阅在容器中布置构件。)
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. 许多JComponent类都有setter和getter方法。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.对于那些没有相应setter方法的非JComponent子类,您可以通过创建子类并重写这些方法来设置组件的首选、最大或最小大小。
void setAlignmentX(float)
void setAlignmentY(float)
Set the alignment along the x- or y- axis. 沿x-轴或y-轴设置对齐。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. 该值应为0到1之间的数字,其中0表示沿原点的对齐,1表示距原点最远的对齐,0.5表示居中,依此类推。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. 获取组件沿x-轴或y-轴的对齐。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.对于没有相应setter方法的非JComponent子类,可以通过创建子类并重写这些方法来设置组件的对齐方式。
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 the ComponentOrientation property of this container and all the components contained within it. 设置此容器及其包含的所有组件的ComponentOrientation属性。See Setting the Container's Orientation for more information.有关详细信息,请参阅设置容器的方向
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.使用此方法的单参数版本时,调用者负责创建返回结果的Dimension实例。
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.获取组件原点相对于父对象左上角的当前xy坐标(以像素为单位)。
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.使用此方法的单参数版本时,调用者负责创建返回结果的Rectangle实例。
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 of getLocation method, the caller is responsible for creating the Point instance in which the result is returned.使用getLocation方法的单参数版本时,调用者负责创建返回结果的Point实例。
Point getLocationOnScreen() Returns the position relative to the upper left corner of the screen.返回相对于屏幕左上角的位置。
Insets getInsets() Get the size of the component's border.获取组件边框的大小。
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. 两个int参数按顺序指定xyUse 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 two int arguments specify width and height, in that order. 两个int参数按顺序指定宽度和高度。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 four int arguments specify x, y, width, and height, in that order. 四个int参数依次指定xywidthheightUse these methods to position and size a component when you are not using a layout manager.在不使用布局管理器时,使用这些方法来定位和调整零部件的大小。

Previous page: Using Top-Level Containers
Next page: Using Text Components