Awt 简明教程
AWT Quick Guide
Graphical User Interface
图形用户界面 (GUI) 通过一些图形组件提供用户交互。例如,我们底层的操作系统还通过窗口、框架、面板、按钮、文本字段、文本区域、列表框、组合框、标签、复选框等提供 GUI。这些都称为组件。使用这些组件,我们可以为应用程序创建一个交互式用户界面。
Graphical User Interface (GUI) offers user interaction via some graphical components. For example our underlying Operating System also offers GUI via window,frame,Panel, Button, Textfield, TextArea, Listbox, Combobox, Label, Checkbox etc. These all are known as components. Using these components we can create an interactive user interface for an application.
GUI 根据激发的事件向最终用户提供结果。GUI 完全基于事件。例如,单击按钮、关闭窗口、打开窗口、在文本区域中键入内容等。这些活动称为事件。GUI 使最终用户可以更容易使用一个应用程序。它还使它们更有趣。
GUI provides result to end user in response to raised events.GUI is entirely based events. For example clicking over a button, closing a window, opening a window, typing something in a textarea etc. These activities are known as events.GUI makes it easier for the end user to use an application. It also makes them interesting.
Basic Terminologies
Term |
Description |
Component |
Component is an object having a graphical representation that can be displayed on the screen and that can interact with the user. For examples buttons, checkboxes, list and scrollbars of a graphical user interface. |
Container |
Container object is a component that can contain other components.Components added to a container are tracked in a list. The order of the list will define the components' front-to-back stacking order within the container. If no index is specified when adding a component to a container, it will be added to the end of the list. |
Panel |
Panel provides space in which an application can attach any other components, including other panels. |
Window |
Window is a rectangular area which is displayed on the screen. In different window we can execute different program and display different data. Window provide us with multitasking environment. A window must have either a frame, dialog, or another window defined as its owner when it’s constructed. |
Frame |
A Frame is a top-level window with a title and a border. The size of the frame includes any area designated for the border. Frame encapsulates window. It and has a title bar, menu bar, borders, and resizing corners. |
Canvas |
Canvas component represents a blank rectangular area of the screen onto which the application can draw. Application can also trap input events from the use from that blank area of Canvas component. |
Examples of GUI based Applications
以下是基于 GUI 的应用程序的一些示例。
Following are some of the examples for GUI based applications.
-
Automated Teller Machine (ATM)
-
Airline Ticketing System
-
Information Kiosks at railway stations
-
Mobile Applications
-
Navigation Systems
Advantages of GUI over CUI
-
GUI provides graphical icons to interact while the CUI (Character User Interface) offers the simple text-based interfaces.
-
GUI makes the application more entertaining and interesting on the other hand CUI does not.
-
GUI offers click and execute environment while in CUI every time we have to enter the command for a task.
-
New user can easily interact with graphical user interface by the visual indicators but it is difficult in Character user interface.
-
GUI offers a lot of controls of file system and the operating system while in CUI you have to use commands which is difficult to remember.
-
Windows concept in GUI allow the user to view, manipulate and control the multiple applications at once while in CUI user can control one task at a time.
-
GUI provides multitasking environment so as the CUI also does but CUI does not provide same ease as the GUI do.
-
Using GUI it is easier to control and navigate the operating system which becomes very slow in command user interface. GUI can be easily customized.
Environment Setup
本部分指导您如何在计算机上下载和设置 Java。请按照以下步骤设置环境。
This section guides you on how to download and set up Java on your machine. Please follow the following steps to set up the environment.
Java SE 可以从链接 Download Java 中免费获得。所以你可以根据你的操作系统下载一个版本。
Java SE is freely available from the link Download Java. So you download a version based on your operating system.
按照说明下载 Java 并运行 .exe 以在你的计算机上安装 Java。一旦在计算机上安装了 Java,就需要设置环境变量以指向正确的安装目录:
Follow the instructions to download java and run the .exe to install Java on your machine. Once you installed Java on your machine, you would need to set environment variables to point to correct installation directories:
Setting up the path for windows 2000/XP:
假设你已将 Java 安装在 c:\Program Files\java\jdk 目录中:
Assuming you have installed Java in c:\Program Files\java\jdk directory:
-
Right-click on 'My Computer' and select 'Properties'.
-
Click on the 'Environment variables' button under the 'Advanced' tab.
-
Now alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
Setting up the path for windows 95/98/ME:
假设你已将 Java 安装在 c:\Program Files\java\jdk 目录中:
Assuming you have installed Java in c:\Program Files\java\jdk directory:
-
Edit the 'C:\autoexec.bat' file and add the following line at the end: 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'
Setting up the path for Linux, UNIX, Solaris, FreeBSD:
环境变量 PATH 应设置为指向已安装 Java 二进制文件的位置。如果您在执行此操作时遇到问题,请参阅您的 shell 文档。
Environment variable PATH should be set to point to where the java binaries have been installed. Refer to your shell documentation if you have trouble doing this.
例如,如果您用 bash 作为您的 shell,则您将向您 '.bashrc: export PATH=/path/to/java:$PATH' 的末尾添加以下行
Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'
Popular Java Editors:
要编写 Java 程序,您需要一个文本编辑器。市场上还有一些更复杂的 IDE,但目前,您可以考虑以下选项之一:
To write your java programs you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following:
-
Notepad : On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
-
*Netbeans :*is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html.
-
Eclipse : is also a java IDE developed by the eclipse open source community and can be downloaded from http://www.eclipse.org/.
AWT Controls
每个用户界面都考虑以下三个主要方面:
Every user interface considers the following three main aspects:
-
UI elements : Thes are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex which we will cover in this tutorial.
-
Layouts: They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in Layout chapter.
-
Behavior: These are events which occur when the user interacts with UI elements. This part will be covered in Event Handling chapter.
每个 AWT 控件都从 Component 类继承属性。
Every AWT controls inherits properties from Component class.
AWT Component Class
Introduction
类 Component 是 AWT 的非菜单用户界面控件的抽象基类。Component 表示一个带有图形表示的对象。
The class Component is the abstract base class for the non menu user-interface controls of AWT. Component represents an object with graphical representation.
Class declaration
以下是 java.awt.Component 类的声明:
Following is the declaration for java.awt.Component class:
public abstract class Component
extends Object
implements ImageObserver, MenuContainer, Serializable
Field
以下是 java.awt.Component 类的字段:
Following are the fields for java.awt.Component class:
-
static float BOTTOM_ALIGNMENT — Ease-of-use constant for getAlignmentY.
-
static float CENTER_ALIGNMENT — Ease-of-use constant for getAlignmentY and getAlignmentX.
-
static float LEFT_ALIGNMENT — Ease-of-use constant for getAlignmentX.
-
static float RIGHT_ALIGNMENT — Ease-of-use constant for getAlignmentX.
-
static float TOP_ALIGNMENT — Ease-of-use constant for getAlignmentY().
Class constructors
S.N. |
Constructor & Description |
1 |
*protected Component() * This creates a new Component. |
Class methods
S.N. |
Method & Description |
1 |
*boolean action(Event evt, Object what) * Deprecated. As of JDK version 1.1, should register this component as ActionListener on component which fires action events. |
2 |
void add(PopupMenu popup) Adds the specified popup menu to the component. |
3 |
*void addComponentListener(ComponentListener l) * Adds the specified component listener to receive component events from this component. |
4 |
*void addFocusListener(FocusListener l) * Adds the specified focus listener to receive focus events from this component when this component gains input focus. |
5 |
void addHierarchyBoundsListener(HierarchyBoundsListener l) Adds the specified hierarchy bounds listener to receive hierarchy bounds events from this component when the hierarchy to which this container belongs changes. |
6 |
void addHierarchyListener(HierarchyListener l) Adds the specified hierarchy listener to receive hierarchy changed events from this component when the hierarchy to which this container belongs changes. |
7 |
void addInputMethodListener(InputMethodListener l) Adds the specified input method listener to receive input method events from this component. |
8 |
void addKeyListener(KeyListener l) Adds the specified key listener to receive key events from this component. |
9 |
void addMouseListener(MouseListener l) Adds the specified mouse listener to receive mouse events from this component. |
10 |
void addMouseMotionListener(MouseMotionListener l) Adds the specified mouse motion listener to receive mouse motion events from this component. |
11 |
void addMouseWheelListener(MouseWheelListener l) Adds the specified mouse wheel listener to receive mouse wheel events from this component. |
12 |
void addNotify() Makes this Component displayable by connecting it to a native screen resource. |
13 |
void addPropertyChangeListener(PropertyChangeListener listener) Adds a PropertyChangeListener to the listener list. |
14 |
void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) Adds a PropertyChangeListener to the listener list for a specific property. |
15 |
void applyComponentOrientation(ComponentOrientation orientation) Sets the ComponentOrientation property of this component and all components contained within it. |
16 |
boolean areFocusTraversalKeysSet(int id) Returns whether the Set of focus traversal keys for the given focus traversal operation has been explicitly defined for this Component. |
17 |
int checkImage(Image image, ImageObserver observer) Returns the status of the construction of a screen representation of the specified image. |
18 |
int checkImage(Image image,int width,int height, ImageObserver observer) Returns the status of the construction of a screen representation of the specified image. |
19 |
boolean contains(int x,int y) Checks whether this component "contains" the specified point, where x and y are defined to be relative to the coordinate system of this component. |
20 |
boolean contains(Point p) Checks whether this component "contains" the specified point, where the point’s x and y coordinates are defined to be relative to the coordinate system of this component. |
21 |
Image createImage(ImageProducer producer) Creates an image from the specified image producer. |
22 |
Image createImage(int width,int height) Creates an off-screen drawable image to be used for double buffering. |
23 |
VolatileImage createVolatileImage(int width,int height) Creates a volatile off-screen drawable image to be used for double buffering. |
24 |
VolatileImage createVolatileImage(int width,int height, ImageCapabilities caps) Creates a volatile off-screen drawable image, with the given capabilities. |
25 |
void deliverEvent(Event e) Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e). |
26 |
void disable() Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean). |
27 |
protected void disableEvents(long eventsToDisable) Disables the events defined by the specified event mask parameter from being delivered to this component. |
28 |
void dispatchEvent(AWTEvent e) Dispatches an event to this component or one of its sub components. |
29 |
void doLayout() Prompts the layout manager to lay out this component. |
30 |
void enable() Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean). |
31 |
void enable(boolean b) Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean). |
32 |
protected void enableEvents(long eventsToEnable) Enables the events defined by the specified event mask parameter to be delivered to this component. |
33 |
void enableInputMethods(boolean enable) Enables or disables input method support for this component. |
34 |
protected void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) Support for reporting bound property changes for boolean properties. |
35 |
void firePropertyChange(String propertyName, byte oldValue, byte newValue) Reports a bound property change. |
36 |
void firePropertyChange(String propertyName, char oldValue, char newValue) Reports a bound property change. |
37 |
void firePropertyChange(String propertyName, double oldValue, double newValue) Reports a bound property change. |
38 |
void firePropertyChange(String propertyName, float oldValue, float newValue) Reports a bound property change. |
39 |
void firePropertyChange(String propertyName, long oldValue, long newValue) Reports a bound property change. |
40 |
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) Support for reporting bound property changes for Object properties. |
41 |
void firePropertyChange(String propertyName, short oldValue, short newValue) Reports a bound property change. |
42 |
AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this Component. |
43 |
float getAlignmentX() Returns the alignment along the x axis. |
44 |
float getAlignmentY() Returns the alignment along the y axis. |
45 |
Color getBackground() Gets the background color of this component. |
46 |
int getBaseline(int width,int height) Returns the baseline. |
47 |
Component.BaselineResizeBehavior getBaselineResizeBehavior() Returns an enum indicating how the baseline of the component changes as the size changes. |
48 |
Rectangle getBounds() Gets the bounds of this component in the form of a Rectangle object. |
49 |
Rectangle getBounds(Rectangle rv) Stores the bounds of this component into return value rv and return rv. |
50 |
ColorModel getColorModel() Gets the instance of ColorModel used to display the component on the output device. |
51 |
Component getComponentAt(int x,int y) Determines if this component or one of its immediate subcomponents contains the (x, y) location, and if so, returns the containing component. |
52 |
Component getComponentAt(Point p) Returns the component or subcomponent that contains the specified point. |
53 |
ComponentListener[] getComponentListeners() Returns an array of all the component listeners registered on this component. |
54 |
ComponentOrientation getComponentOrientation() Retrieves the language-sensitive orientation that is to be used to order the elements or text within this component. |
55 |
Cursor getCursor() Gets the cursor set in the component. |
56 |
DropTarget getDropTarget() Gets the DropTarget associated with this Component. |
57 |
Container getFocusCycleRootAncestor() Returns the Container which is the focus cycle root of this Component’s focus traversal cycle. |
58 |
FocusListener[] getFocusListeners() Returns an array of all the focus listeners registered on this component. |
59 |
Set<AWTKeyStroke> getFocusTraversalKeys(int id) Returns the Set of focus traversal keys for a given traversal operation for this Component. |
60 |
boolean getFocusTraversalKeysEnabled() Returns whether focus traversal keys are enabled for this Component. |
61 |
Font getFont() Gets the font of this component. |
62 |
FontMetrics getFontMetrics(Font font) Gets the font metrics for the specified font. |
63 |
Color getForeground() Gets the foreground color of this component. |
64 |
Graphics getGraphics() Creates a graphics context for this component. |
65 |
GraphicsConfiguration getGraphicsConfiguration() Gets the GraphicsConfiguration associated with this Component. |
66 |
int getHeight() Returns the current height of this component. |
67 |
HierarchyBoundsListener[] getHierarchyBoundsListeners() Returns an array of all the hierarchy bounds listeners registered on this component. |
68 |
HierarchyListener[] getHierarchyListeners() Returns an array of all the hierarchy listeners registered on this component. |
69 |
boolean getIgnoreRepaint() |
70 |
InputContext getInputContext() Gets the input context used by this component for handling the communication with input methods when text is entered in this component. |
71 |
InputMethodListener[] getInputMethodListeners() Returns an array of all the input method listeners registered on this component. |
72 |
InputMethodRequests getInputMethodRequests() Gets the input method request handler which supports requests from input methods for this component. |
73 |
KeyListener[] getKeyListeners() Returns an array of all the key listeners registered on this component. |
74 |
<T extends EventListener> T[] getListeners(Class<T> listenerType) Returns an array of all the objects currently registered as FooListeners upon this Component. |
75 |
Locale getLocale() Gets the locale of this component. |
76 |
Point getLocation() Gets the location of this component in the form of a point specifying the component’s top-left corner. |
77 |
Point getLocation(Point rv) Stores the x,y origin of this component into return value rv and return rv. |
78 |
Point getLocationOnScreen() Gets the location of this component in the form of a point specifying the component’s top-left corner in the screen’s coordinate space. |
79 |
Dimension getMaximumSize() Gets the maximum size of this component. |
80 |
Dimension getMinimumSize() Gets the mininimum size of this component. |
81 |
MouseListener[] getMouseListeners() Returns an array of all the mouse listeners registered on this component. |
82 |
MouseMotionListener[] getMouseMotionListeners() Returns an array of all the mouse motion listeners registered on this component. |
83 |
Point getMousePosition() Returns the position of the mouse pointer in this Component’s coordinate space if the Component is directly under the mouse pointer, otherwise returns null. |
84 |
MouseWheelListener[] getMouseWheelListeners() Returns an array of all the mouse wheel listeners registered on this component. |
85 |
String getName() Gets the name of the component. |
86 |
Container getParent() Gets the parent of this component. |
87 |
java.awt.peer.ComponentPeer getPeer() Deprecated. As of JDK version 1.1, programs should not directly manipulate peers; replaced by boolean isDisplayable(). |
88 |
Dimension getPreferredSize() Gets the preferred size of this component. |
89 |
PropertyChangeListener[] getPropertyChangeListeners() Returns an array of all the property change listeners registered on this component. |
90 |
PropertyChangeListener[] getPropertyChangeListeners(String propertyName) Returns an array of all the listeners which have been associated with the named property. |
91 |
Dimension getSize() Returns the size of this component in the form of a Dimension object. |
92 |
Dimension getSize(Dimension rv)Stores the width/height of this component into *return value rv and return rv.* |
93 |
Toolkit getToolkit() Gets the toolkit of this component. |
94 |
Object getTreeLock() Gets this component’s locking object (the object that owns the thread sychronization monitor) for AWT component-tree and layout operations. |
95 |
int getWidth() Returns the current width of this component. |
96 |
int getX() Returns the current x coordinate of the components origin. |
97 |
int getY() Returns the current y coordinate of the components origin. |
98 |
boolean gotFocus(Event evt, Object what) Deprecated. As of JDK version 1.1, replaced by processFocusEvent(FocusEvent) . |
99 |
boolean handleEvent(Event evt) Deprecated. As of JDK version 1.1 replaced by processEvent(AWTEvent). |
100 |
boolean hasFocus() Returns true if this Component is the focus owner. |
101 |
void hide() Deprecated. As of JDK version 1.1, replaced by setVisible(boolean). |
102 |
boolean imageUpdate(Image img,int infoflags,int x,int y,int w,int h) Repaints the component when the image has changed. |
103 |
boolean inside(int x,int y) Deprecated. As of JDK version 1.1, replaced by contains(int, int). |
104 |
void invalidate() Invalidates this component. |
105 |
boolean isBackgroundSet() Returns whether the background color has been explicitly set for this Component. |
106 |
boolean isCursorSet() Returns whether the cursor has been explicitly set for this Component. |
107 |
boolean isDisplayable() Determines whether this component is displayable. |
108 |
boolean isDoubleBuffered() Returns true if this component is painted to an offscreen image (buffer) that’s copied to the screen later. |
109 |
boolean isEnabled() Determines whether this component is enabled. |
110 |
boolean isFocusable() Returns whether this Component can be focused. |
111 |
boolean isFocusCycleRoot(Container container) Returns whether the specified Container is the focus cycle root of this Component’s focus traversal cycle. |
112 |
boolean isFocusOwner() Returns true if this Component is the focus owner. |
113 |
boolean isFocusTraversable() Deprecated. As of 1.4, replaced by isFocusable(). |
114 |
boolean isFontSet() Returns whether the font has been explicitly set for this Component. |
115 |
boolean isForegroundSet() Returns whether the foreground color has been explicitly set for this Component. |
116 |
boolean isLightweight() A lightweight component doesn’t have a native toolkit peer. |
117 |
boolean isMaximumSizeSet() Returns true if the maximum size has been set to a non-null value otherwise returns false. |
118 |
boolean isMinimumSizeSet() Returns whether or not setMinimumSize has been invoked with a non-null value. |
119 |
boolean isOpaque() Returns true if this component is completely opaque, returns false by default. |
120 |
boolean isPreferredSizeSet() Returns true if the preferred size has been set to a non-null value otherwise returns false. |
121 |
boolean isShowing() Determines whether this component is showing on screen. |
122 |
boolean isValid() Determines whether this component is valid. |
123 |
boolean isVisible() Determines whether this component should be visible when its parent is visible. |
124 |
boolean keyDown(Event evt,int key) Deprecated. As of JDK version 1.1, replaced by processKeyEvent(KeyEvent). |
125 |
boolean keyUp(Event evt,int key) Deprecated. As of JDK version 1.1, replaced by processKeyEvent(KeyEvent). |
126 |
void layout() Deprecated. As of JDK version 1.1, replaced by doLayout(). |
127 |
void list() Prints a listing of this component to the standard system output stream System.out. |
128 |
void list(PrintStream out) Prints a listing of this component to the specified output stream. |
129 |
void list(PrintStream out,int indent) Prints out a list, starting at the specified indentation, to the specified print stream. |
130 |
void list(PrintWriter out) Prints a listing to the specified print writer. |
131 |
void list(PrintWriter out,int indent) Prints out a list, starting at the specified indentation, to the specified print writer. |
132 |
Component locate(int x,int y) Deprecated. As of JDK version 1.1, replaced by getComponentAt(int, int). |
133 |
Point location() Deprecated. As of JDK version 1.1, replaced by getLocation(). |
134 |
boolean lostFocus(Event evt, Object what) Deprecated. As of JDK version 1.1, replaced by processFocusEvent(FocusEvent). |
135 |
boolean mouseDown(Event evt,int x,int y) Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent). |
136 |
boolean mouseDrag(Event evt,int x,int y) Deprecated. As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent). |
137 |
boolean mouseEnter(Event evt,int x,int y) Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent). |
138 |
boolean mouseExit(Event evt,int x,int y) Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).. |
139 |
boolean mouseMove(Event evt,int x,int y) Deprecated. As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent).. |
140 |
boolean mouseUp(Event evt,int x,int y) Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent). |
141 |
void move(int x,int y) Deprecated. As of JDK version 1.1, replaced by setLocation(int, int). |
142 |
void nextFocus() Deprecated. As of JDK version 1.1, replaced by transferFocus(). |
143 |
void paint(Graphics g) Paints this component. |
144 |
void paintAll(Graphics g) Paints this component and all of its subcomponents. |
145 |
boolean postEvent(Event e) Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent). |
146 |
boolean prepareImage(Image image,int width,int height, ImageObserver observer) Prepares an image for rendering on this component at the specified width and height. |
147 |
void print(Graphics g) Prints this component. |
148 |
void printAll(Graphics g) Prints this component and all of its subcomponents. |
149 |
protectedvoid processComponentEvent(ComponentEvent e) Processes component events occurring on this component by dispatching them to any registered ComponentListener objects. |
150 |
protected void processEvent(AWTEvent e) Processes events occurring on this component. |
151 |
protected void processFocusEvent(FocusEvent e) Processes focus events occurring on this component by dispatching them to any registered FocusListener objects. |
152 |
protected void processHierarchyBoundsEvent(HierarchyEvent e) Processes hierarchy bounds events occurring on this component by dispatching them to any registered HierarchyBoundsListener objects. |
153 |
protected void processHierarchyEvent(HierarchyEvent e) Processes hierarchy events occurring on this component by dispatching them to any registered HierarchyListener objects. |
154 |
protectedvoid processInputMethodEvent(InputMethodEvent e) Processes input method events occurring on this component by dispatching them to any registered InputMethodListener objects. |
155 |
protected void processKeyEvent(KeyEvent e) Processes key events occurring on this component by dispatching them to any registered KeyListener objects. |
156 |
protected void processMouseEvent(MouseEvent e) Processes mouse events occurring on this component by dispatching them to any registered MouseListener objects. |
157 |
protected void processMouseMotionEvent(MouseEvent e) Processes mouse motion events occurring on this component by dispatching them to any registered MouseMotionListener objects. |
158 |
protected void processMouseWheelEvent(MouseWheelEvent e) Processes mouse wheel events occurring on this component by dispatching them to any registered MouseWheelListener objects. |
159 |
void remove(MenuComponent popup) Removes the specified popup menu from the component. |
160 |
void removeComponentListener(ComponentListener l) Removes the specified component listener so that it no longer receives component events from this component. |
161 |
void removeFocusListener(FocusListener l) Removes the specified focus listener so that it no longer receives focus events from this component. |
162 |
void removeHierarchyBoundsListener(HierarchyBoundsListener l) Removes the specified hierarchy bounds listener so that it no longer receives hierarchy bounds events from this component. |
163 |
void removeHierarchyListener(HierarchyListener l) Removes the specified hierarchy listener so that it no longer receives hierarchy changed events from this component. |
164 |
void removeInputMethodListener(InputMethodListener l) Removes the specified input method listener so that it no longer receives input method events from this component. |
165 |
void removeKeyListener(KeyListener l) Removes the specified key listener so that it no longer receives key events from this component. |
166 |
void removeMouseListener(MouseListener l) Removes the specified mouse listener so that it no longer receives mouse events from this component. |
167 |
void removeMouseMotionListener(MouseMotionListener l) Removes the specified mouse motion listener so that it no longer receives mouse motion events from this component. |
168 |
void removeMouseWheelListener(MouseWheelListener l) Removes the specified mouse wheel listener so that it no longer receives mouse wheel events from this component. |
169 |
void removeNotify() Makes this Component undisplayable by destroying it native screen resource. |
170 |
void removePropertyChangeListener(PropertyChangeListener listener) Removes a PropertyChangeListener from the listener list. |
171 |
void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) Removes a PropertyChangeListener from the listener list for a specific property. |
172 |
void repaint() Repaints this component. |
173 |
void repaint(int x,int y,int width,int height) Repaints the specified rectangle of this component. |
174 |
void repaint(long tm) Repaints the component. |
175 |
void repaint(long tm,int x,int y,int width,int height) Repaints the specified rectangle of this component within tm milliseconds. |
176 |
void requestFocus() Requests that this Component get the input focus, and that this Component’s top-level ancestor become the focused Window. |
177 |
protected boolean requestFocus(boolean temporary) Requests that this Component get the input focus, and that this Component’s top-level ancestor become the focused Window. |
178 |
boolean requestFocusInWindow() Requests that this Component get the input focus, if this Component’s top-level ancestor is already the focused Window. |
179 |
protected boolean requestFocusInWindow(boolean temporary) Requests that this Component get the input focus, if this Component’s top-level ancestor is already the focused Window. |
180 |
void reshape(int x,int y,int width,int height) Deprecated. As of JDK version 1.1, replaced by setBounds(int, int, int, int). |
181 |
void resize(Dimension d) Deprecated. As of JDK version 1.1, replaced by setSize(Dimension). |
182 |
void resize(int width,int height) Deprecated. As of JDK version 1.1, replaced by setSize(int, int). |
183 |
void setBackground(Color c) Sets the background color of this component. |
184 |
void setBounds(int x,int y,int width,int height) Moves and resizes this component. |
185 |
void setBounds(Rectangle r) Moves and resizes this component to conform to the new bounding rectangle r. |
186 |
void setComponentOrientation(ComponentOrientation o) Sets the language-sensitive orientation that is to be used to order the elements or text within this component. |
187 |
void setCursor(Cursor cursor) Sets the cursor image to the specified cursor. |
188 |
void setDropTarget(DropTarget dt) Associate a DropTarget with this component. |
189 |
void setEnabled(boolean b) Enables or disables this component, depending on the value of the parameter b. |
190 |
void setFocusable(boolean focusable) Sets the focusable state of this Component to the specified value. |
191 |
void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes) Sets the focus traversal keys for a given traversal operation for this Component. |
192 |
void setFocusTraversalKeysEnabled(boolean focusTraversalKeysEnabled) Sets whether focus traversal keys are enabled for this Component. |
193 |
void setFont(Font f) Sets the font of this component. |
194 |
void setForeground(Color c) Sets the foreground color of this component. |
195 |
void setIgnoreRepaint(boolean ignoreRepaint) Sets whether or not paint messages received from the operating system should be ignored. |
196 |
void setLocale(Locale l) Sets the locale of this component. |
197 |
void setLocation(int x,int y) Moves this component to a new location. |
198 |
void setLocation(Point p) Moves this component to a new location. |
199 |
void setMaximumSize(Dimension maximumSize) Sets the maximum size of this component to a constant value. |
200 |
void setMinimumSize(Dimension minimumSize) Sets the minimum size of this component to a constant value. |
201 |
void setName(String name) Sets the name of the component to the specified string. |
202 |
void setPreferredSize(Dimension preferredSize) Sets the preferred size of this component to a constant value. |
203 |
void setSize(Dimension d) Resizes this component so that it has width d.width and height d.height. |
204 |
void setSize(int width,int height) Resizes this component so that it has width width and height height. |
205 |
void setVisible(boolean b) Shows or hides this component depending on the value of parameter b. |
206 |
void show() Deprecated. As of JDK version 1.1, replaced by setVisible(boolean). |
207 |
void show(boolean b) Deprecated. As of JDK version 1.1, replaced by setVisible(boolean). |
208 |
Dimension size() Deprecated. As of JDK version 1.1, replaced by getSize(). |
209 |
String toString() Returns a string representation of this component and its values. |
210 |
void transferFocus() Transfers the focus to the next component, as though this Component were the focus owner. |
211 |
void transferFocusBackward() Transfers the focus to the previous component, as though this Component were the focus owner. |
212 |
void transferFocusUpCycle() Transfers the focus up one focus traversal cycle. |
213 |
void update(Graphics g) Updates this component. |
214 |
void validate() Ensures that this component has a valid layout. |
215 |
Rectangle bounds() Deprecated. As of JDK version 1.1, replaced by getBounds(). |
216 |
protected AWTEvent coalesceEvents(AWTEvent existingEvent, AWTEvent newEvent) Potentially coalesce an event being posted with an existing event. |
217 |
protected String paramString() Returns a string representing the state of this component. |
218 |
protected void firePropertyChange(String propertyName,int oldValue,int newValue) Support for reporting bound property changes for integer properties. |
219 |
Dimension preferredSize() Deprecated. As of JDK version 1.1, replaced by getPreferredSize(). |
220 |
boolean prepareImage(Image image, ImageObserver observer) Prepares an image for rendering on this component. |
221 |
Dimension minimumSize() Deprecated. As of JDK version 1.1, replaced by getMinimumSize(). |
AWT Label Class
Introduction
Label 是一个被动控件,因为它在用户访问时不会创建任何事件。Label 控件是 Label 的对象。Label 显示一行只读文本。但是,该文本可以由应用程序员进行更改,但终端用户无法以任何方式进行更改。
Label is a passive control because it does not create any event when accessed by the user. The label control is an object of Label. A label displays a single line of read-only text. However the text can be changed by the application programmer but cannot be changed by the end user in any way.
Class declaration
以下是 java.awt.Label 类的声明:
Following is the declaration for java.awt.Label class:
public class Label
extends Component
implements Accessible
Field
以下是 java.awt.Component 类的字段:
Following are the fields for java.awt.Component class:
-
static int CENTER — Indicates that the label should be centered.
-
static int LEFT — Indicates that the label should be left justified.
-
static int RIGHT — Indicates that the label should be right justified.
Class constructors
S.N. |
Constructor & Description |
1 |
*Label() * Constructs an empty label. |
2 |
*Label(String text) * Constructs a new label with the specified string of text, left justified. |
3 |
*Label(String text, int alignment) * Constructs a new label that presents the specified string of text with the specified alignment. |
Class methods
S.N. |
Method & Description |
1 |
*void addNotify() * Creates the peer for this label. |
2 |
*AccessibleContext getAccessibleContext() * Gets the AccessibleContext associated with this Label. |
3 |
*int getAlignment() * Gets the current alignment of this label. |
4 |
*String getText() * Gets the text of this label. |
5 |
*protected String paramString() * Returns a string representing the state of this Label. |
6 |
*void setAlignment(int alignment) * Sets the alignment for this label to the specified alignment. |
7 |
*void setText(String text) * Sets the text for this label to the specified text. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.awt.Component
-
java.lang.Object
Label Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showLabelDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showLabelDemo(){
headerLabel.setText("Control in action: Label");
Label label = new Label();
label.setText("Welcome to TutorialsPoint AWT Tutorial.");
label.setAlignment(Label.CENTER);
label.setBackground(Color.GRAY);
label.setForeground(Color.WHITE);
controlPanel.add(label);
mainFrame.setVisible(true);
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
验证以下输出
Verify the following output
AWT Button Class
Introduction
按钮是一个有标签的控件组件,并在按下时生成一个事件。当按钮被按下并释放时,AWT 通过调用按钮上的 processEvent 来向按钮发送 ActionEvent 的一个实例。按钮的 processEvent 方法接收针对按钮的所有事件;它通过调用自己的 processActionEvent 方法来传递一个动作事件。后者方法将动作事件传递给对由此按钮生成的动作事件已登记兴趣的任何动作侦听器。
Button is a control component that has a label and generates an event when pressed. When a button is pressed and released, AWT sends an instance of ActionEvent to the button, by calling processEvent on the button. The button’s processEvent method receives all events for the button; it passes an action event along by calling its own processActionEvent method. The latter method passes the action event on to any action listeners that have registered an interest in action events generated by this button.
如果一个应用程序需要基于按钮被按下并释放来执行一些动作,则它应实现 ActionListener 并调用按钮的 addActionListener 方法来注册新侦听器以接收来自此按钮的事件。应用程序可以利用按钮的动作命令作为消息传递协议。
If an application wants to perform some action based on a button being pressed and released, it should implement ActionListener and register the new listener to receive events from this button, by calling the button’s addActionListener method. The application can make use of the button’s action command as a messaging protocol.
Class declaration
以下是 java.awt.Button 类的声明:
Following is the declaration for java.awt.Button class:
public class Button
extends Component
implements Accessible
Class constructors
S.N. |
Constructor & Description |
1 |
*Button() * Constructs a button with an empty string for its label. |
2 |
*Button(String text) * Constructs a new button with specified label. |
Class methods
S.N. |
Method & Description |
1 |
*void addActionListener(ActionListener l) * Adds the specified action listener to receive action events from this button. |
2 |
*void addNotify() * Creates the peer of the button. |
3 |
*AccessibleContext getAccessibleContext() * Gets the AccessibleContext associated with this Button. |
4 |
*String getActionCommand() * Returns the command name of the action event fired by this button. |
5 |
*ActionListener[] getActionListeners() * Returns an array of all the action listeners registered on this button. |
6 |
*String getLabel() * Gets the label of this button. |
7 |
*<T extends EventListener> T[] getListeners(Class<T> listenerType) * Returns an array of all the objects currently registered as FooListeners upon this Button. |
8 |
*protected String paramString() * Returns a string representing the state of this Button. |
9 |
*protected void processActionEvent(ActionEvent e) * Processes action events occurring on this button by dispatching them to any registered ActionListener objects. |
10 |
*protected void processEvent(AWTEvent e) * Processes events on this button. |
11 |
*void removeActionListener(ActionListener l) * Removes the specified action listener so that it no longer receives action events from this button. |
12 |
*void setActionCommand(String command) * Sets the command name for the action event fired by this button. |
13 |
*void setLabel(String label) * Sets the button’s label to be the specified string. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.awt.Component
-
java.lang.Object
Button Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showButtonDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showButtonDemo(){
headerLabel.setText("Control in action: Button");
Button okButton = new Button("OK");
Button submitButton = new Button("Submit");
Button cancelButton = new Button("Cancel");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Ok Button clicked.");
}
});
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Submit Button clicked.");
}
});
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Cancel Button clicked.");
}
});
controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
验证以下输出
Verify the following output
AWT CheckBox Class
Introduction
Checkbox 控件用于打开(true)或关闭(false)选项。每个复选框都有一个标签,表示复选框的作用。可以通过单击复选框来更改其状态。
Checkbox control is used to turn an option on(true) or off(false). There is label for each checkbox representing what the checkbox does.The state of a checkbox can be changed by clicking on it.
Class declaration
以下是 java.awt.Checkbox 类的声明:
Following is the declaration for java.awt.Checkbox class:
public class Checkbox
extends Component
implements ItemSelectable,Accessible
Class constructors
S.N. |
Constructor & Description |
1 |
*Checkbox() * Creates a check box with an empty string for its label. |
2 |
*Checkbox(String label) * Creates a check box with the specified label. |
3 |
*Checkbox(String label, boolean state) * Creates a check box with the specified label and sets the specified state. |
4 |
*Checkbox(String label, boolean state, CheckboxGroup group) * Constructs a Checkbox with the specified label, set to the specified state, and in the specified check box group. |
5 |
*Checkbox(String label, CheckboxGroup group, boolean state) * Creates a check box with the specified label, in the specified check box group, and set to the specified state. |
Class methods
S.N. |
Method & Description |
1 |
*void addItemListener(ItemListener l) * Adds the specified item listener to receive item events from this check box. |
2 |
*void addNotify() * Creates the peer of the Checkbox. |
3 |
*AccessibleContext getAccessibleContext() * Gets the AccessibleContext associated with this Checkbox. |
4 |
*CheckboxGroup getCheckboxGroup() * Determines this check box’s group. |
5 |
*ItemListener[] getItemListeners() * Returns an array of all the item listeners registered on this checkbox. |
6 |
*String getLabel() * Gets the label of this check box. |
7 |
*<T extends EventListener>T[] getListeners(Class<T> listenerType) * Returns an array of all the objects currently registered as FooListeners upon this Checkbox. |
8 |
*Object[] getSelectedObjects() * Returns an array (length 1) containing the checkbox label or null if the checkbox is not selected. |
9 |
boolean getState() * Determines whether this check box is in the *on or off state. |
10 |
*protected String paramString() * Returns a string representing the state of this Checkbox. |
11 |
*protected void processEvent(AWTEvent e) * Processes events on this check box. |
12 |
*protected void processItemEvent(ItemEvent e) * Processes item events occurring on this check box by dispatching them to any registered ItemListener objects. |
13 |
*void removeItemListener(ItemListener l) * Removes the specified item listener so that the item listener no longer receives item events from this check box. |
14 |
*void setCheckboxGroup(CheckboxGroup g) * Sets this check box’s group to the specified check box group. |
15 |
*void setLabel(String label) * Sets this check box’s label to be the string argument. |
16 |
*void setState(boolean state) * Sets the state of this check box to the specified state. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.awt.Component
-
java.lang.Object
CheckBox Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showCheckBoxDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showCheckBoxDemo(){
headerLabel.setText("Control in action: CheckBox");
Checkbox chkApple = new Checkbox("Apple");
Checkbox chkMango = new Checkbox("Mango");
Checkbox chkPeer = new Checkbox("Peer");
chkApple.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Apple Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
chkMango.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Mango Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
chkPeer.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Peer Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
controlPanel.add(chkApple);
controlPanel.add(chkMango);
controlPanel.add(chkPeer);
mainFrame.setVisible(true);
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
验证以下输出
Verify the following output
AWT CheckBoxGroup Class
Introduction
CheckboxGroup 类用于对复选框集合进行分组。
The CheckboxGroup class is used to group the set of checkbox.
Class declaration
以下是 java.awt.CheckboxGroup 类的声明:
Following is the declaration for java.awt.CheckboxGroup class:
public class CheckboxGroup
extends Object
implements Serializable
Class constructors
S.N. |
Constructor & Description |
1 |
*CheckboxGroup() () * Creates a new instance of CheckboxGroup. |
Class methods
S.N. |
Method & Description |
1 |
*Checkbox getCurrent() * Deprecated. As of JDK version 1.1, replaced by getSelectedCheckbox(). |
2 |
*Checkbox getSelectedCheckbox() * Gets the current choice from this check box group. |
3 |
void setCurrent(Checkbox box) Deprecated. As of JDK version 1.1, replaced by setSelectedCheckbox(Checkbox). |
4 |
*void setSelectedCheckbox(Checkbox box) * Sets the currently selected check box in this group to be the specified check box. |
5 |
*String toString() * Returns a string representation of this check box group, including the value of its current selection. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.lang.Object
CheckBoxGroup Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showCheckBoxGroupDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showCheckBoxGroupDemo(){
headerLabel.setText("Control in action: CheckBoxGroup");
CheckboxGroup fruitGroup = new CheckboxGroup();
Checkbox chkApple = new Checkbox("Apple",fruitGroup,true);
Checkbox chkMango = new Checkbox("Mango",fruitGroup,false);
Checkbox chkPeer = new Checkbox("Peer",fruitGroup,false);
statusLabel.setText("Apple Checkbox: checked");
chkApple.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Apple Checkbox: checked");
}
});
chkMango.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Mango Checkbox: checked");
}
});
chkPeer.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Peer Checkbox: checked");
}
});
controlPanel.add(chkApple);
controlPanel.add(chkMango);
controlPanel.add(chkPeer);
mainFrame.setVisible(true);
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
验证以下输出
Verify the following output
AWT List Class
Introduction
List 表示一个文本项目列表。列表可以配置为用户可以选择一个项目或多个项目。
The List represents a list of text items. The list can be configured that user can choose either one item or multiple items.
Class declaration
以下是 java.awt.List 类的声明:
Following is the declaration for java.awt.List class:
public class List
extends Component
implements ItemSelectable, Accessible
Class constructors
S.N. |
Constructor & Description |
1 |
*List() * Creates a new scrolling list. |
2 |
*List(int rows) * Creates a new scrolling list initialized with the specified number of visible lines. |
3 |
*List(int rows, boolean multipleMode) * Creates a new scrolling list initialized to display the specified number of rows. |
Class methods
S.N. |
Method & Description |
1 |
*void add(String item) * Adds the specified item to the end of scrolling list. |
2 |
*void add(String item, int index) * Adds the specified item to the the scrolling list at the position indicated by the index. |
3 |
*void addActionListener(ActionListener l) * Adds the specified action listener to receive action events from this list. |
4 |
*void addItem(String item) * Deprecated. replaced by add(String). |
5 |
*void addItem(String item, int index) * Deprecated. replaced by add(String, int). |
6 |
*void addItemListener(ItemListener l) * Adds the specified item listener to receive item events from this list. |
7 |
*void addNotify() * Creates the peer for the list. |
8 |
*boolean allowsMultipleSelections() * Deprecated. As of JDK version 1.1, replaced by isMultipleMode(). |
9 |
*void clear() * Deprecated. As of JDK version 1.1, replaced by removeAll(). |
10 |
*int countItems() * Deprecated. As of JDK version 1.1, replaced by getItemCount(). |
11 |
void delItem(int position) Deprecated. replaced by remove(String) and remove(int). |
12 |
*void delItems(int start, int end) * Deprecated. As of JDK version 1.1, Not for public use in the future. This method is expected to be retained only as a package private method. |
13 |
*void deselect(int index) * Deselects the item at the specified index. |
14 |
*AccessibleContext getAccessibleContext() * Gets the AccessibleContext associated with this List. |
15 |
*ActionListener[] getActionListeners() * Returns an array of all the action listeners registered on this list. |
16 |
*String getItem(int index) * Gets the item associated with the specified index. |
17 |
*int getItemCount() * Gets the number of items in the list. |
18 |
*ItemListener[] getItemListeners() * Returns an array of all the item listeners registered on this list. |
19 |
*String[] getItems() * Gets the items in the list. |
20 |
*Dimension getMinimumSize() * Determines the minimum size of this scrolling list. |
21 |
*Dimension getMinimumSize(int rows) * Gets the minumum dimensions for a list with the specified number of rows. |
22 |
*Dimension getPreferredSize() * Gets the preferred size of this scrolling list. |
23 |
*Dimension getPreferredSize(int rows) * Gets the preferred dimensions for a list with the specified number of rows. |
24 |
*int getRows() * Gets the number of visible lines in this list. |
25 |
*int getSelectedIndex() * Gets the index of the selected item on the list, |
26 |
*int[] getSelectedIndexes() * Gets the selected indexes on the list. |
27 |
*String getSelectedItem() * Gets the selected item on this scrolling list. |
28 |
*String[] getSelectedItems() * Gets the selected items on this scrolling list. |
29 |
*Object[] getSelectedObjects() * Gets the selected items on this scrolling list in an array of Objects. |
30 |
*int getVisibleIndex() * Gets the index of the item that was last made visible by the method makeVisible. |
31 |
*boolean isIndexSelected(int index) * Determines if the specified item in this scrolling list is selected. |
32 |
*boolean isMultipleMode() * Determines whether this list allows multiple selections. |
33 |
*boolean isSelected(int index) * Deprecated. As of JDK version 1.1, replaced by isIndexSelected(int). |
34 |
*void makeVisible(int index) * Makes the item at the specified index visible. |
35 |
*Dimension minimumSize() * Deprecated. As of JDK version 1.1, replaced by getMinimumSize(). |
36 |
* Dimension minimumSize(int rows) * Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int). |
37 |
*protected String paramString() * Returns the parameter string representing the state of this scrolling list. |
38 |
*Dimension preferredSize() * Deprecated. As of JDK version 1.1, replaced by getPreferredSize(). |
39 |
*Dimension preferredSize(int rows) * Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int). |
40 |
*protected void processActionEvent(ActionEvent e) * Processes action events occurring on this component by dispatching them to any registered ActionListener objects. |
41 |
*protected void processEvent(AWTEvent e) * Processes events on this scrolling list. |
42 |
*protected void processItemEvent(ItemEvent e) * Processes item events occurring on this list by dispatching them to any registered ItemListener objects. |
43 |
*void remove(int position) * Removes the item at the specified position from this scrolling list. |
44 |
*void remove(String item) * Removes the first occurrence of an item from the list. |
45 |
*void removeActionListener(ActionListener l) * Removes the specified action listener so that it no longer receives action events from this list. |
46 |
*void removeAll() * Removes all items from this list. |
47 |
*void removeItemListener(ItemListener l) * Removes the specified item listener so that it no longer receives item events from this list. |
48 |
*void removeNotify() * Removes the peer for this list. |
49 |
*void replaceItem(String newValue, int index) * Replaces the item at the specified index in the scrolling list with the new string. |
50 |
*void select(int index) * Selects the item at the specified index in the scrolling list. |
51 |
*void setMultipleMode(boolean b) * Sets the flag that determines whether this list allows multiple selections. |
52 |
*void setMultipleSelections(boolean b) * Deprecated. As of JDK version 1.1, replaced by setMultipleMode(boolean). |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.awt.Component
-
java.lang.Object
List Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showListDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showListDemo(){
headerLabel.setText("Control in action: List");
final List fruitList = new List(4,false);
fruitList.add("Apple");
fruitList.add("Grapes");
fruitList.add("Mango");
fruitList.add("Peer");
final List vegetableList = new List(4,true);
vegetableList.add("Lady Finger");
vegetableList.add("Onion");
vegetableList.add("Potato");
vegetableList.add("Tomato");
Button showButton = new Button("Show");
showButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Fruits Selected: "
+ fruitList.getItem(fruitList.getSelectedIndex());
data += ", Vegetables selected: ";
for(String vegetable:vegetableList.getSelectedItems()){
data += vegetable + " ";
}
statusLabel.setText(data);
}
});
controlPanel.add(fruitList);
controlPanel.add(vegetableList);
controlPanel.add(showButton);
mainFrame.setVisible(true);
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
验证以下输出
Verify the following output
AWT TextField Class
Introduction
textField 组件允许用户编辑单行文本。当用户在文本字段中键入键时,事件会发送给 TextField。键事件可能是按键按下、松开或键入。键事件将传递给已注册的 KeyListener。如果在该文本字段上启用了 ActionEvent,还可能出现 ActionEvent,然后可能通过按下“返回”键来引发 ActionEvent。
The textField component allows the user to edit single line of text.When the user types a key in the text field the event is sent to the TextField. The key event may be key pressed, Key released or key typed. The key event is passed to the registered KeyListener. It is also possible to for an ActionEvent if the ActionEvent is enabled on the textfield then ActionEvent may be fired by pressing the return key.
Class declaration
下面为 java.awt.TextField 类中的声明:
Following is the declaration for java.awt.TextField class:
public class TextField
extends TextComponent
Class constructors
S.N. |
Constructor & Description |
1 |
*TextField() * Constructs a new text field. |
2 |
*TextField(int columns) * Constructs a new empty text field with the specified number of columns. |
3 |
*TextField(String text) * Constructs a new text field initialized with the specified text. |
4 |
*TextField(String text, int columns) * Constructs a new text field initialized with the specified text to be displayed, and wide enough to hold the specified number of columns. |
Class methods
S.N. |
Method & Description |
1 |
*void addActionListener(ActionListener l) * Adds the specified action listener to receive action events from this text field. |
2 |
*void addNotify() * Creates the TextField’s peer. |
3 |
*boolean echoCharIsSet() * Indicates whether or not this text field has a character set for echoing. |
4 |
*AccessibleContext getAccessibleContext() * Gets the AccessibleContext associated with this TextField. |
5 |
*ActionListener[] getActionListeners() * Returns an array of all the action listeners registered on this textfield. |
6 |
*int getColumns() * Gets the number of columns in this text field. |
7 |
*char getEchoChar() * Gets the character that is to be used for echoing. |
8 |
*<T extends EventListener> T[] getListeners(Class<T> listenerType) * Returns an array of all the objects currently registered as FooListeners upon this TextField. |
9 |
*Dimension getMinimumSize() * Gets the minumum dimensions for this text field. |
10 |
Dimension getMinimumSize(int columns) Gets the minumum dimensions for a text field with the specified number of columns. |
11 |
*Dimension getPreferredSize() * Gets the preferred size of this text field. |
12 |
*Dimension getPreferredSize(int columns) * Gets the preferred size of this text field with the specified number of columns. |
13 |
*Dimension minimumSize() * Deprecated. As of JDK version 1.1, replaced by getMinimumSize(). |
14 |
*Dimension minimumSize(int columns) * Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int). |
15 |
*protected String paramString() * Returns a string representing the state of this TextField. |
16 |
*Dimension preferredSize() * Deprecated. As of JDK version 1.1, replaced by getPreferredSize(). |
17 |
*Dimension preferredSize(int columns) * Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int). |
18 |
*protected void processActionEvent(ActionEvent e) * Processes action events occurring on this text field by dispatching them to any registered ActionListener objects. |
19 |
*protected void processEvent(AWTEvent e) * Processes events on this text field. |
20 |
*void removeActionListener(ActionListener l) * Removes the specified action listener so that it no longer receives action events from this text field. |
21 |
*void setColumns(int columns) * Sets the number of columns in this text field. |
22 |
*void setEchoChar(char c) * Sets the echo character for this text field. |
23 |
*void setEchoCharacter(char c) * Deprecated. As of JDK version 1.1, replaced by setEchoChar(char). |
24 |
*void setText(String t) * Sets the text that is presented by this text component to be the specified text. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.awt.TextComponent
-
java.awt.Component
-
java.lang.Object
TextField Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showTextFieldDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showTextFieldDemo(){
headerLabel.setText("Control in action: TextField");
Label namelabel= new Label("User ID: ", Label.RIGHT);
Label passwordLabel = new Label("Password: ", Label.CENTER);
final TextField userText = new TextField(6);
final TextField passwordText = new TextField(6);
passwordText.setEchoChar('*');
Button loginButton = new Button("Login");
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Username: " + userText.getText();
data += ", Password: " + passwordText.getText();
statusLabel.setText(data);
}
});
controlPanel.add(namelabel);
controlPanel.add(userText);
controlPanel.add(passwordLabel);
controlPanel.add(passwordText);
controlPanel.add(loginButton);
mainFrame.setVisible(true);
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
验证以下输出
Verify the following output
AWT TextArea Class
Introduction
AWT 中的 TextArea 控件为我们提供了多行编辑器区域。用户可以根据需要在此处输入尽可能多的文本。当文本区域中的文本大于可视区域时,将自动显示滚动条,帮助我们将文本向上和向下以及向右和向左滚动。
The TextArea control in AWT provide us multiline editor area. The user can type here as much as he wants. When the text in the text area become larger than the viewable area the scroll bar is automatically appears which help us to scroll the text up & down and right & left.
Class declaration
以下是 java.awt.TextArea 类的声明:
Following is the declaration for java.awt.TextArea class:
public class TextArea
extends TextComponent
Field
以下是 java.awt.TextArea 类的字段:
Following are the fields for java.awt.TextArea class:
-
*static int SCROLLBARS_BOTH * — Create and display both vertical and horizontal scrollbars.
-
*static int SCROLLBARS_HORIZONTAL_ONLY * — Create and display horizontal scrollbar only.
-
*static int SCROLLBARS_NONE * — Do not create or display any scrollbars for the text area.
-
static int SCROLLBARS_VERTICAL_ONLY — Create and display vertical scrollbar only.
Class constructors
S.N. |
Constructor & Description |
1 |
*TextArea() * Constructs a new text area with the empty string as text. |
2 |
*TextArea(int rows, int columns) * Constructs a new text area with the specified number of rows and columns and the empty string as text. |
3 |
*TextArea(String text) * Constructs a new text area with the specified text. |
4 |
*TextArea(String text, int rows, int columns) * Constructs a new text area with the specified text, and with the specified number of rows and columns. |
5 |
*TextArea(String text, int rows, int columns, int scrollbars) * Constructs a new text area with the specified text, and with the rows, columns, and scroll bar visibility as specified. |
Class methods
S.N. |
Method & Description |
1 |
*void addNotify() * Creates the TextArea’s peer. |
2 |
*void append(String str) * Appends the given text to the text area’s current text. |
3 |
*void appendText(String str) * Deprecated. As of JDK version 1.1, replaced by append(String). |
4 |
*AccessibleContext getAccessibleContext() * Returns the AccessibleContext associated with this TextArea. |
5 |
*int getColumns() * Returns the number of columns in this text area. |
6 |
*Dimension getMinimumSize() * Determines the minimum size of this text area. |
7 |
*Dimension getMinimumSize(int rows, int columns) * Determines the minimum size of a text area with the specified number of rows and columns. |
8 |
*Dimension getPreferredSize() * Determines the preferred size of this text area. |
9 |
*Dimension getPreferredSize(int rows, int columns) * Determines the preferred size of a text area with the specified number of rows and columns. |
10 |
*int getRows() * Returns the number of rows in the text area. |
11 |
*int getScrollbarVisibility() * Returns an enumerated value that indicates which scroll bars the text area uses. |
12 |
*void insert(String str, int pos) * Inserts the specified text at the specified position in this text area. |
13 |
*void insertText(String str, int pos) * Deprecated. As of JDK version 1.1, replaced by insert(String, int). |
14 |
*Dimension minimumSize() * Deprecated. As of JDK version 1.1, replaced by getMinimumSize(). |
15 |
*Dimension minimumSize(int rows, int columns) * Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int, int). |
16 |
*protected String paramString() * Returns a string representing the state of this TextArea. |
17 |
*Dimension preferredSize() * Deprecated. As of JDK version 1.1, replaced by getPreferredSize(). |
18 |
*Dimension preferredSize(int rows, int columns) * Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int, int). |
19 |
*void replaceRange(String str, int start, int end) * Replaces text between the indicated start and end positions with the specified replacement text. |
20 |
*void replaceText(String str, int start, int end) * Deprecated. As of JDK version 1.1, replaced by replaceRange(String, int, int). |
21 |
*void setColumns(int columns) * Sets the number of columns for this text area. |
22 |
*void setRows(int rows) * Sets the number of rows for this text area. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.awt.TextComponent
-
java.awt.Component
-
java.lang.Object
TextArea Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showTextAreaDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showTextAreaDemo(){
headerLabel.setText("Control in action: TextArea");
Label commentlabel= new Label("Comments: ", Label.RIGHT);
final TextArea commentTextArea = new TextArea("This is a AWT tutorial "
+"to make GUI application in Java.",5,30);
Button showButton = new Button("Show");
showButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText( commentTextArea.getText());
}
});
controlPanel.add(commentlabel);
controlPanel.add(commentTextArea);
controlPanel.add(showButton);
mainFrame.setVisible(true);
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
验证以下输出
Verify the following output
AWT Choice Class
Introduction
使用选项控件显示弹出式选项菜单。所选选项显示在菜单顶部。
Choice control is used to show pop up menu of choices. Selected choice is shown on the top of the menu.
Class declaration
以下是 java.awt.Choice 类的声明:
Following is the declaration for java.awt.Choice class:
public class Choice
extends Component
implements ItemSelectable, Accessible
Class methods
S.N. |
Method & Description |
1 |
*void add(String item) * Adds an item to this Choice menu. |
2 |
*void addItem(String item) * Obsolete as of Java 2 platform v1.1. |
3 |
*void addItemListener(ItemListener l) * Adds the specified item listener to receive item events from this Choice menu. |
4 |
*void addNotify() * Creates the Choice’s peer. |
5 |
*int countItems() * Deprecated. As of JDK version 1.1, replaced by getItemCount(). |
6 |
*AccessibleContext getAccessibleContext() * Gets the AccessibleContext associated with this Choice. |
7 |
*String getItem(int index) * Gets the string at the specified index in this Choice menu. |
8 |
*int getItemCount() * Returns the number of items in this Choice menu. |
9 |
*ItemListener[] getItemListeners() * Returns an array of all the item listeners registered on this choice. |
10 |
*<T extends EventListener> T[] getListeners(Class<T> listenerType) * Returns an array of all the objects currently registered as FooListeners upon this Choice. |
11 |
*int getSelectedIndex() * Returns the index of the currently selected item. |
12 |
*String getSelectedItem() * Gets a representation of the current choice as a string. |
13 |
*Object[] getSelectedObjects() * Returns an array (length 1) containing the currently selected item. |
14 |
*void insert(String item, int index) * Inserts the item into this choice at the specified position. |
15 |
protected String paramString() Returns a string representing the state of this Choice menu. |
16 |
*protected void processEvent(AWTEvent e) * Processes events on this choice. |
17 |
*protected void processItemEvent(ItemEvent e) * Processes item events occurring on this Choice menu by dispatching them to any registered ItemListener objects. |
18 |
*void remove(int position) * Removes an item from the choice menu at the specified position. |
19 |
*void remove(String item) * Removes the first occurrence of item from the Choice menu. |
20 |
*void removeAll() * Removes all items from the choice menu. |
21 |
*void removeItemListener(ItemListener l) * Removes the specified item listener so that it no longer receives item events from this Choice menu. |
22 |
*void select(int pos) * Sets the selected item in this Choice menu to be the item at the specified position. |
23 |
*void select(String str) * Sets the selected item in this Choice menu to be the item whose name is equal to the specified string. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.awt.Component
-
java.lang.Object
Choice Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showChoiceDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showChoiceDemo(){
headerLabel.setText("Control in action: Choice");
final Choice fruitChoice = new Choice();
fruitChoice.add("Apple");
fruitChoice.add("Grapes");
fruitChoice.add("Mango");
fruitChoice.add("Peer");
Button showButton = new Button("Show");
showButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Fruit Selected: "
+ fruitChoice.getItem(fruitChoice.getSelectedIndex());
statusLabel.setText(data);
}
});
controlPanel.add(fruitChoice);
controlPanel.add(showButton);
mainFrame.setVisible(true);
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
验证以下输出
Verify the following output
AWT Canvas Class
Introduction
Canvas 控件表示应用程序可以在其中绘制某些内容或可以接收用户创建的输入的矩形区域。
Canvas control represents a rectangular area where application can draw something or can receive inputs created by user.
Class declaration
以下是 java.awt.Canvas 类的声明:
Following is the declaration for java.awt.Canvas class:
public class Canvas
extends Component
implements Accessible
Class constructors
S.N. |
Constructor & Description |
1 |
*Canvas() * Constructs a new Canvas. |
2 |
*Canvas(GraphicsConfiguration config) * Constructs a new Canvas given a GraphicsConfiguration object. |
Class methods
S.N. |
Method & Description |
1 |
*void addNotify() * Creates the peer of the canvas. |
2 |
*void createBufferStrategy(int numBuffers) * Creates a new strategy for multi-buffering on this component. |
3 |
*void createBufferStrategy(int numBuffers, BufferCapabilities caps) * Creates a new strategy for multi-buffering on this component with the required buffer capabilities. |
4 |
*AccessibleContext getAccessibleContext() * Gets the AccessibleContext associated with this Canvas. |
5 |
*BufferStrategy getBufferStrategy() * Returns the BufferStrategy used by this component. |
6 |
*void paint(Graphics g) * Paints this canvas. |
7 |
*void pdate(Graphics g) * Updates this canvas. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.awt.Component
-
java.lang.Object
Canvas Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showCanvasDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showCanvasDemo(){
headerLabel.setText("Control in action: Canvas");
controlPanel.add(new MyCanvas());
mainFrame.setVisible(true);
}
class MyCanvas extends Canvas {
public MyCanvas () {
setBackground (Color.GRAY);
setSize(300, 300);
}
public void paint (Graphics g) {
Graphics2D g2;
g2 = (Graphics2D) g;
g2.drawString ("It is a custom canvas area", 70, 70);
}
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
验证以下输出
Verify the following output
AWT Image Class
Introduction
图像控件是用于表示图形图像的所有图像类的超类。
Image control is superclass for all image classes representing graphical images.
Class declaration
以下是 java.awt.Image 类的声明:
Following is the declaration for java.awt.Image class:
public abstract class Image
extends Object
Field
以下是 java.awt.Image 类的字段:
Following are the fields for java.awt.Image class:
-
*protected float accelerationPriority * — Priority for accelerating this image.
-
*static int SCALE_AREA_AVERAGING * — Use the Area Averaging image scaling algorithm.
-
*static int SCALE_DEFAULT * — Use the default image-scaling algorithm.
-
*static int SCALE_FAST * — Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.
-
*static int SCALE_REPLICATE * — Use the image scaling algorithm embodied in the ReplicateScaleFilter class.
-
*static int SCALE_SMOOTH * — Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.
-
*static Object UndefinedProperty * — The UndefinedProperty object should be returned whenever a property which was not defined for a particular image is fetched.
Class methods
S.N. |
Method & Description |
1 |
*void flush() * Flushes all reconstructable resources being used by this Image object. |
2 |
*float getAccelerationPriority() * Returns the current value of the acceleration priority hint. |
3 |
*ImageCapabilities getCapabilities(GraphicsConfiguration gc) * Returns an ImageCapabilities object which can be inquired as to the capabilities of this Image on the specified GraphicsConfiguration. |
4 |
*abstract Graphics getGraphics() * Creates a graphics context for drawing to an off-screen image. |
5 |
*abstract int getHeight(ImageObserver observer) * Determines the height of the image. |
6 |
*abstract Object getProperty(String name, ImageObserver observer) * Gets a property of this image by name. |
7 |
*Image getScaledInstance(int width, int height, int hints) * Creates a scaled version of this image. |
8 |
*abstract ImageProducer getSource() * Gets the object that produces the pixels for the image. |
9 |
*abstract int getWidth(ImageObserver observer) * Determines the width of the image. |
10 |
*void setAccelerationPriority(float priority) * Sets a hint for this image about how important acceleration is. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.lang.Object
Image Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showImageDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showImageDemo(){
headerLabel.setText("Control in action: Image");
controlPanel.add(new ImageComponent("resources/java.jpg"));
mainFrame.setVisible(true);
}
class ImageComponent extends Component {
BufferedImage img;
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
public ImageComponent(String path) {
try {
img = ImageIO.read(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
return new Dimension(img.getWidth(), img.getHeight());
}
}
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
验证以下输出
Verify the following output
AWT Scrollbar Class
Introduction
滚动条控件用于表示滚动条组件,以便用户能够在值范围内选择。
Scrollbar control represents a scroll bar component in order to enable user to select from range of values.
Class declaration
以下是 java.awt.Scrollbar 类的声明:
Following is the declaration for java.awt.Scrollbar class:
public class Scrollbar
extends Component
implements Adjustable, Accessible
Field
以下是 java.awt.Image 类的字段:
Following are the fields for java.awt.Image class:
-
*static int HORIZONTAL * --A constant that indicates a horizontal scroll bar.
-
*static int VERTICAL * --A constant that indicates a vertical scroll bar.
Class constructors
S.N. |
Constructor & Description |
1 |
*Scrollbar() * Constructs a new vertical scroll bar. |
2 |
*Scrollbar(int orientation) * Constructs a new scroll bar with the specified orientation. |
3 |
*Scrollbar(int orientation, int value, int visible, int minimum, int maximum) * Constructs a new scroll bar with the specified orientation, initial value, visible amount, and minimum and maximum values. |
Class methods
S.N. |
Method & Description |
1 |
*void addAdjustmentListener(AdjustmentListener l) * Adds the specified adjustment listener to receive instances of AdjustmentEvent from this scroll bar. |
2 |
*void addNotify() * Creates the Scrollbar’s peer. |
3 |
*int getBlockIncrement() * Gets the block increment of this scroll bar. |
4 |
*int getLineIncrement() * Deprecated. As of JDK version 1.1, replaced by getUnitIncrement(). |
5 |
*int getMaximum() * Gets the maximum value of this scroll bar. |
6 |
*int getMinimum() * Gets the minimum value of this scroll bar. |
7 |
int getOrientation() Returns the orientation of this scroll bar. |
8 |
*int getPageIncrement() * Deprecated. As of JDK version 1.1, replaced by getBlockIncrement(). |
9 |
int getUnitIncrement() Gets the unit increment for this scrollbar. |
10 |
*int getValue() * Gets the current value of this scroll bar. |
11 |
boolean getValueIsAdjusting() Returns true if the value is in the process of changing as a result of actions being taken by the user. |
12 |
*int getVisible() * Deprecated. As of JDK version 1.1, replaced by getVisibleAmount(). |
13 |
*int getVisibleAmount() * Gets the visible amount of this scroll bar. |
14 |
*protected String paramString() * Returns a string representing the state of this Scrollbar. |
15 |
*protected void processAdjustmentEvent(AdjustmentEvent e) * Processes adjustment events occurring on this scrollbar by dispatching them to any registered AdjustmentListener objects. |
16 |
*protected * |
1 |
*void processEvent(AWTEvent e) * Processes events on this scroll bar. |
17 |
*void removeAdjustmentListener(AdjustmentListener l) * Removes the specified adjustment listener so that it no longer receives instances of AdjustmentEvent from this scroll bar. |
18 |
*void setBlockIncrement(int v) * Sets the block increment for this scroll bar. |
19 |
*void setLineIncrement(int v) * Deprecated. As of JDK version 1.1, replaced by setUnitIncrement(int). |
20 |
*void setMaximum(int newMaximum) * Sets the maximum value of this scroll bar. |
21 |
*void setMinimum(int newMinimum) * Sets the minimum value of this scroll bar. |
22 |
*void setOrientation(int orientation) * Sets the orientation for this scroll bar. |
23 |
*void setPageIncrement(int v) * Deprecated. As of JDK version 1.1, replaced by setBlockIncrement(). |
24 |
*void setUnitIncrement(int v) * Sets the unit increment for this scroll bar. |
25 |
*void setValue(int newValue) * Sets the value of this scroll bar to the specified value. |
26 |
*void setValueIsAdjusting(boolean b) * Sets the valueIsAdjusting property. |
27 |
*void setValues(int value, int visible, int minimum, int maximum) * Sets the values of four properties for this scroll bar: value, visibleAmount, minimum, and maximum. |
28 |
*void setVisibleAmount(int newAmount) * Sets the visible amount of this scroll bar. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.awt.Component
-
java.lang.Object
Scrollbar Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showScrollbarDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showScrollbarDemo(){
headerLabel.setText("Control in action: Scrollbar");
final Scrollbar horizontalScroller = new Scrollbar(Scrollbar.HORIZONTAL);
final Scrollbar verticalScroller = new Scrollbar();
verticalScroller.setOrientation(Scrollbar.VERTICAL);
horizontalScroller.setMaximum (100);
horizontalScroller.setMinimum (1);
verticalScroller.setMaximum (100);
verticalScroller.setMinimum (1);
horizontalScroller.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
statusLabel.setText("Horozontal: "
+horizontalScroller.getValue()
+" ,Vertical: "
+ verticalScroller.getValue());
}
});
verticalScroller.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
statusLabel.setText("Horozontal: "
+horizontalScroller.getValue()
+" ,Vertical: "+ verticalScroller.getValue());
}
});
controlPanel.add(horizontalScroller);
controlPanel.add(verticalScroller);
mainFrame.setVisible(true);
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
验证以下输出
Verify the following output
AWT Dialog Class
Introduction
对话控件代表一个顶级窗口,带有标题和边框,用于获取来自用户的某种形式的输入。
Dialog control represents a top-level window with a title and a border used to take some form of input from the user.
Class declaration
以下是 java.awt.Dialog 类的声明:
Following is the declaration for java.awt.Dialog class:
public class Dialog
extends Window
Field
以下是 java.awt.Image 类的字段:
Following are the fields for java.awt.Image class:
-
*static Dialog.ModalityType DEFAULT_MODALITY_TYPE * — Default modality type for modal dialogs.
Class constructors
S.N. |
Constructor & Description |
1 |
*Dialog(Dialog owner) * Constructs an initially invisible, modeless Dialog with the specified owner Dialog and an empty title. |
2 |
*Dialog(Dialog owner, String title) * Constructs an initially invisible, modeless Dialog with the specified owner Dialog and title. |
3 |
*Dialog(Dialog owner, String title, boolean modal) * Constructs an initially invisible Dialog with the specified owner Dialog, title, and modality. |
4 |
*Dialog(Dialog owner, String title, boolean modal, GraphicsConfiguration gc) * Constructs an initially invisible Dialog with the specified owner Dialog, title, modality and GraphicsConfiguration. |
5 |
*Dialog(Frame owner) * Constructs an initially invisible, modeless Dialog with the specified owner Frame and an empty title. |
6 |
*Dialog(Frame owner, boolean modal) * Constructs an initially invisible Dialog with the specified owner Frame and modality and an empty title. |
7 |
*Dialog(Frame owner, String title) * Constructs an initially invisible, modeless Dialog with the specified owner Frame and title. |
8 |
*Dialog(Frame owner, String title, boolean modal) * Constructs an initially invisible Dialog with the specified owner Frame, title and modality. |
9 |
*Dialog(Frame owner, String title, boolean modal, GraphicsConfiguration gc) * Constructs an initially invisible Dialog with the specified owner Frame, title, modality, and GraphicsConfiguration. |
10 |
*Dialog(Window owner) * Constructs an initially invisible, modeless Dialog with the specified owner Window and an empty title. |
11 |
*Dialog(Window owner, Dialog.ModalityType modalityType) * Constructs an initially invisible Dialog with the specified owner Window and modality and an empty title. |
12 |
*Dialog(Window owner, String title) * Constructs an initially invisible, modeless Dialog with the specified owner Window and title. |
13 |
*Dialog(Window owner, String title, Dialog.ModalityType modalityType) * Constructs an initially invisible Dialog with the specified owner Window, title and modality. |
14 |
*Dialog(Window owner, String title, Dialog.ModalityType modalityType, GraphicsConfiguration gc) * Constructs an initially invisible Dialog with the specified owner Window, title, modality and GraphicsConfiguration |
Class methods
S.N. |
Method & Description |
1 |
*void addNotify() * Makes this Dialog displayable by connecting it to a native screen resource. |
2 |
AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this Dialog. |
3 |
*Dialog.ModalityType getModalityType() * Returns the modality type of this dialog. |
4 |
*String getTitle() * Gets the title of the dialog. |
5 |
void hide() Deprecated. As of JDK version 1.5, replaced by setVisible(boolean). |
6 |
*boolean isModal() * Indicates whether the dialog is modal. |
7 |
*boolean isResizable() * Indicates whether this dialog is resizable by the user. |
8 |
*boolean isUndecorated() * Indicates whether this dialog is undecorated. |
9 |
*protected String paramString() * Returns a string representing the state of this dialog. |
10 |
*void setModal(boolean modal) * Specifies whether this dialog should be modal. |
11 |
*void setModalityType(Dialog.ModalityType type) * Sets the modality type for this dialog. |
12 |
*void setResizable(boolean resizable) * Sets whether this dialog is resizable by the user. |
13 |
*void setTitle(String title) * Sets the title of the Dialog. |
14 |
*void setUndecorated(boolean undecorated) * Disables or enables decorations for this dialog. |
15 |
*void setVisible(boolean b) * Shows or hides this Dialog depending on the value of parameter b. |
16 |
*void show() * Deprecated. As of JDK version 1.5, replaced by setVisible(boolean). |
17 |
*void toBack() * If this Window is visible, sends this Window to the back and may cause it to lose focus or activation if it is the focused or active Window. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.awt.Window
-
java.awt.Component
-
java.lang.Object
Dialog Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showDialogDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showDialogDemo(){
headerLabel.setText("Control in action: Dialog");
Button showAboutDialogButton = new Button("Show About Dialog");
showAboutDialogButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AboutDialog aboutDialog = new AboutDialog(mainFrame);
aboutDialog.setVisible(true);
}
});
controlPanel.add(showAboutDialogButton);
mainFrame.setVisible(true);
}
class AboutDialog extends Dialog {
public AboutDialog(Frame parent){
super(parent, true);
setBackground(Color.gray);
setLayout(new BorderLayout());
Panel panel = new Panel();
panel.add(new Button("Close"));
add("South", panel);
setSize(200,200);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
dispose();
}
});
}
public boolean action(Event evt, Object arg){
if(arg.equals("Close")){
dispose();
return true;
}
return false;
}
public void paint(Graphics g){
g.setColor(Color.white);
g.drawString("TutorialsPoint.Com", 25,70 );
g.drawString("Version 1.0", 60, 90);
}
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
验证以下输出
Verify the following output
AWT FileDialog Class
Introduction
FileDialog 控件表示用户可从中选择文件的一个对话框窗口。
FileDialog control represents a dialog window from which the user can select a file.
Class declaration
以下是 java.awt.FileDialog 类的声明:
Following is the declaration for java.awt.FileDialog class:
public class FileDialog
extends Dialog
Field
以下是 java.awt.Image 类的字段:
Following are the fields for java.awt.Image class:
-
*static int LOAD * — This constant value indicates that the purpose of the file dialog window is to locate a file from which to read.
-
*static int SAVE * — This constant value indicates that the purpose of the file dialog window is to locate a file to which to write.
Class constructors
S.N. |
Constructor & Description |
1 |
*FileDialog(Dialog parent) * Creates a file dialog for loading a file. |
2 |
FileDialog(Dialog parent, String title) Creates a file dialog window with the specified title for loading a file. |
3 |
*FileDialog(Dialog parent, String title, int mode) * Creates a file dialog window with the specified title for loading or saving a file. |
4 |
FileDialog(Frame parent) Creates a file dialog for loading a file. |
5 |
*FileDialog(Frame parent, String title) * Creates a file dialog window with the specified title for loading a file. |
6 |
*FileDialog(Frame parent, String title, int mode) * Creates a file dialog window with the specified title for loading or saving a file. |
Class methods
S.N. |
Method & Description |
1 |
*void addNotify() * Creates the file dialog’s peer. |
2 |
*String getDirectory() * Gets the directory of this file dialog. |
3 |
*String getFile() * Gets the selected file of this file dialog. |
4 |
*FilenameFilter getFilenameFilter() * Determines this file dialog’s filename filter. |
5 |
*int getMode() * Indicates whether this file dialog box is for loading from a file or for saving to a file. |
6 |
*protected String paramString() * Returns a string representing the state of this FileDialog window. |
7 |
*void setDirectory(String dir) * Sets the directory of this file dialog window to be the specified directory. |
8 |
*void setFile(String file) * Sets the selected file for this file dialog window to be the specified file. |
9 |
*void setFilenameFilter(FilenameFilter filter) * Sets the filename filter for this file dialog window to the specified filter. |
10 |
*void setMode(int mode) * Sets the mode of the file dialog. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.awt.Dialog
-
java.awt.Window
-
java.awt.Component
-
java.lang.Object
FileDialog Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showFileDialogDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showFileDialogDemo(){
headerLabel.setText("Control in action: FileDialog");
final FileDialog fileDialog = new FileDialog(mainFrame,"Select file");
Button showFileDialogButton = new Button("Open File");
showFileDialogButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fileDialog.setVisible(true);
statusLabel.setText("File Selected :"
+ fileDialog.getDirectory() + fileDialog.getFile());
}
});
controlPanel.add(showFileDialogButton);
mainFrame.setVisible(true);
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
验证以下输出
Verify the following output
Event Handling
What is an Event?
物体的状态变化称为事件,即事件描述源的状态变化。事件是由于用户与图形用户界面组件的交互而生成的。例如,单击按钮、移动鼠标、通过键盘输入字符、从列表中选择项、滚动页面是由导致事件发生的操作。
Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page are the activities that causes an event to happen.
Types of Event
事件大致可以分为两类:
The events can be broadly classified into two categories:
-
Foreground Events - Those events which require the direct interaction of user.They are generated as consequences of a person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page etc.
-
Background Events - Those events that require the interaction of end user are known as background events. Operating system interrupts, hardware or software failure, timer expires, an operation completion are the example of background events.
What is Event Handling?
事件处理是控制事件并决定在事件发生时应发生什么的机制。此机制包含一个名为事件处理程序的代码,该代码在事件发生时执行。Java 使用委托事件模型来处理事件。此模型定义了用于生成和处理事件的标准机制。让我们简要介绍一下此模型。
Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.Let’s have a brief introduction to this model.
委托事件模型有以下主要参与者:
The Delegation Event Model has the following key participants namely:
-
Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred event to it’s handler. Java provide as with classes for source object.
-
Listener - It is also known as event handler.Listener is responsible for generating response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received , the listener process the event an then returns.
这种方法的好处是用户界面逻辑与生成事件的逻辑完全分离开来。用户界面元素能够将事件的处理委托给单独的代码块。在此模型中,侦听器需要在源对象中注册,以便侦听器能够接收事件通知。这是处理事件的有效方式,因为事件通知仅发送给想要接收它们的侦听器。
The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to the separate piece of code. In this model ,Listener needs to be registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listener that want to receive them.
Steps involved in event handling
-
The User clicks the button and the event is generated.
-
Now the object of concerned event class is created automatically and information about the source and the event get populated with in same object.
-
Event object is forwarded to the method of registered listener class.
-
the method is now get executed and returns.
Points to remember about listener
-
In order to design a listener class we have to develop some listener interfaces.These Listener interfaces forecast some public abstract callback methods which must be implemented by the listener class.
-
If you do not implement the any if the predefined interfaces then your class can not act as a listener class for a source object.
Callback Methods
这些是由 API 提供者提供的,由应用程序程序员定义并由应用程序开发人员调用的方法。在此,回调方法表示事件方法。为了响应事件,Java JRE 将触发回调方法。所有此类回调方法都在侦听器接口中提供。
These are the methods that are provided by API provider and are defined by the application programmer and invoked by the application developer. Here the callback methods represents an event method. In response to an event java jre will fire callback method. All such callback methods are provided in listener interfaces.
如果组件希望某个侦听器侦听其事件,则该源必须将自身注册到侦听器。
If a component wants some listener will listen to it’s events the the source must register itself to the listener.
Event Handling Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showEventDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showEventDemo(){
headerLabel.setText("Control in action: Button");
Button okButton = new Button("OK");
Button submitButton = new Button("Submit");
Button cancelButton = new Button("Cancel");
okButton.setActionCommand("OK");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");
okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if( command.equals( "OK" )) {
statusLabel.setText("Ok Button clicked.");
}
else if( command.equals( "Submit" ) ) {
statusLabel.setText("Submit Button clicked.");
}
else {
statusLabel.setText("Cancel Button clicked.");
}
}
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
验证以下输出
Verify the following output
AWT Event Classes
事件类表示事件。Java 为我们提供了各种事件类,但我们将讨论那些使用频率较高的事件类。
The Event classes represent the event. Java provides us various Event classes but we will discuss those which are more frequently used.
EventObject class
这是派生所有事件状态对象的所有事件类的根类。所有事件都是使用指向对象的引用构建的,即 source ,该对象在逻辑上被视为最初发生相关事件的对象。此类在 java.util 包中定义。
It is the root class from which all event state objects shall be derived. All Events are constructed with a reference to the object, the source, that is logically deemed to be the object upon which the Event in question initially occurred upon. This class is defined in java.util package.
Class declaration
以下是 java.util.EventObject 类的声明:
Following is the declaration for java.util.EventObject class:
public class EventObject
extends Object
implements Serializable
Field
以下是 java.util.EventObject 类的字段:
Following are the fields for java.util.EventObject class:
-
protected Object source — The object on which the Event initially occurred.
Class constructors
S.N. |
Constructor & Description |
1 |
*EventObject(Object source) * Constructs a prototypical Event. |
Class methods
S.N. |
Method & Description |
1 |
Object getSource() The object on which the Event initially occurred. |
2 |
String toString() Returns a String representation of this EventObject. |
AWT AWTEvent Class
它是所有 AWT 事件的根事件类。此类及其子类取代原始的 java.awt.Event 类。此类在 java.awt 包中定义。此类有一个名为getID()的方法,可用于确定事件的类型。
It is the root event class for all AWT events. This class and its subclasses supercede the original java.awt.Event class. This class is defined in java.awt package. This class has a method named getID() that can be used to determine the type of event.
Class declaration
以下是 java.awt.AWTEvent 类的声明:
Following is the declaration for java.awt.AWTEvent class:
public class AWTEvent
extends EventObject
Field
以下是 java.awt.AWTEvent 类的字段:
Following are the fields for java.awt.AWTEvent class:
-
static int ACTION_FIRST — The first number in the range of ids used for action events.
-
*static long ACTION_EVENT_MASK * — The event mask for selecting action events.
-
*static long ADJUSTMENT_EVENT_MASK * — The event mask for selecting adjustment events.
-
*static long COMPONENT_EVENT_MASK * — The event mask for selecting component events.
-
*protected boolean consumed * — Controls whether or not the event is sent back down to the peer once the source has processed it - false means it’s sent to the peer; true means it’s not.
-
*static long CONTAINER_EVENT_MASK * — The event mask for selecting container events.
-
*static long FOCUS_EVENT_MASK * — The event mask for selecting focus events.
-
*static long HIERARCHY_BOUNDS_EVENT_MASK * — The event mask for selecting hierarchy bounds events.
-
*static long HIERARCHY_EVENT_MASK * — The event mask for selecting hierarchy events.
-
*protected int id * — The event’s id.
-
*static long INPUT_METHOD_EVENT_MASK * — The event mask for selecting input method events.
-
*static long INVOCATION_EVENT_MASK * — The event mask for selecting invocation events.
-
*static long ITEM_EVENT_MASK * — The event mask for selecting item events.
-
*static long KEY_EVENT_MASK * — The event mask for selecting key events.
-
*static long MOUSE_EVENT_MASK * — The event mask for selecting mouse events.
-
*static long MOUSE_MOTION_EVENT_MASK * — The event mask for selecting mouse motion events.
-
*static long MOUSE_WHEEL_EVENT_MASK * — The event mask for selecting mouse wheel events.
-
*static long PAINT_EVENT_MASK * — The event mask for selecting paint events.
-
*static int RESERVED_ID_MAX * — The maximum value for reserved AWT event IDs.
-
*static long TEXT_EVENT_MASK * — The event mask for selecting text events.
-
*static long WINDOW_EVENT_MASK * — The event mask for selecting window events.
-
*static long WINDOW_FOCUS_EVENT_MASK * — The event mask for selecting window focus events.
-
*static long WINDOW_STATE_EVENT_MASK * — The event mask for selecting window state events.
Class constructors
S.N. |
Constructor & Description |
1 |
*AWTEvent(Event event) * Constructs an AWTEvent object from the parameters of a 1.0-style event. |
2 |
*AWTEvent(java.lang.Object source, int id) * Constructs an AWTEvent object with the specified source object and type. |
Class methods
S.N. |
Method & Description |
1 |
protected void consume() Consumes this event, if this event can be consumed. |
2 |
int getID() Returns the event type. |
3 |
protected boolean isConsumed() Returns whether this event has been consumed. |
4 |
java.lang.String paramString() Returns a string representing the state of this Event. |
5 |
void setSource(java.lang.Object newSource) Retargets an event to a new source. |
6 |
java.lang.String toString() Returns a String representation of this object. |
AWT ActionEvent Class
该类在 java.awt.event 包中定义。当单击按钮或双击列表项时,将生成 ActionEvent。
This class is defined in java.awt.event package. The ActionEvent is generated when button is clicked or the item of a list is double clicked.
Class declaration
以下是 java.awt.event.ActionEvent 类的声明:
Following is the declaration for java.awt.event.ActionEvent class:
public class ActionEvent
extends AWTEvent
Field
以下是 java.awt.event.ActionEvent 类的字段:
Following are the fields for java.awt.event.ActionEvent class:
-
static int ACTION_FIRST — The first number in the range of ids used for action events.
-
*static int ACTION_LAST * — The last number in the range of ids used for action events.
-
*static int ACTION_PERFORMED * — This event id indicates that a meaningful action occured.
-
*static int ALT_MASK * — The alt modifier.
-
*static int CTRL_MASK * — The control modifier.
-
*static int META_MASK * — The meta modifier.
-
*static int SHIFT_MASK * — The shift modifier.
Class constructors
S.N. |
Constructor & Description |
1 |
ActionEvent(java.lang.Object source, int id, java.lang.String command) Constructs an ActionEvent object. |
2 |
ActionEvent(java.lang.Object source, int id, java.lang.String command, int modifiers) Constructs an ActionEvent object with modifier keys. |
3 |
ActionEvent(java.lang.Object source, int id, java.lang.String command, long when, int modifiers) Constructs an ActionEvent object with the specified modifier keys and timestamp. |
Class methods
S.N. |
Method & Description |
1 |
java.lang.String getActionCommand() Returns the command string associated with this action. |
2 |
int getModifiers() Returns the modifier keys held down during this action event. |
3 |
long getWhen() Returns the timestamp of when this event occurred. |
4 |
java.lang.String paramString() Returns a parameter string identifying this action event. |
AWT InputEvent Class
InputEvent 类是所有组件级输入事件的根事件类。在输入事件的源正常处理它们之前,它们将被传递给侦听器。这允许侦听器和组件子类“使用”事件,以便源不会以其默认方式处理它们。例如,使用按钮组件上的 mousePressed 事件将阻止按钮被激活。
The InputEvent class is root event class for all component-level input events. Input events are delivered to listeners before they are processed normally by the source where they originated. This allows listeners and component subclasses to "consume" the event so that the source will not process them in their default manner. For example, consuming mousePressed events on a Button component will prevent the Button from being activated.
Class declaration
以下是 java.awt.event.InputEvent 类的声明:
Following is the declaration for java.awt.event.InputEvent class:
public abstract class InputEvent
extends ComponentEvent
Field
以下是 java.awt.event.InputEvent 类的字段:
Following are the fields for java.awt.event.InputEvent class:
-
*static int ALT_DOWN_MASK * — The Alt key extended modifier constant.
-
*static int ALT_GRAPH_DOWN_MASK * — The AltGraph key extended modifier constant.
-
*static int ALT_GRAPH_MASK * — The AltGraph key modifier constant.
-
*static int ALT_MASK * — The Alt key modifier constant.
-
*static int BUTTON1_DOWN_MASK * — The Mouse Button1 extended modifier constant.
-
*static int BUTTON1_MASK * — The Mouse Button1 modifier constant.
-
*static int BUTTON2_DOWN_MASK * — The Mouse Button2 extended modifier constant.
-
*static int BUTTON2_MASK * — The Mouse Button2 modifier constant.
-
*static int BUTTON3_DOWN_MASK * — The Mouse Button3 extended modifier constant.
-
*static int BUTTON3_MASK * --The Mouse Button3 modifier constant.
-
*static int CTRL_DOWN_MASK * — The Control key extended modifier constant.
-
*static int CTRL_MASK * — The Control key modifier constant.
-
*static int META_DOWN_MASK * — The Meta key extended modifier constant.
-
*static int META_MASK * — The Meta key modifier constant.
-
*static int SHIFT_DOWN_MASK * — The Shift key extended modifier constant.
-
*static int SHIFT_MASK * — The Shift key modifier constant.
Class methods
S.N. |
Method & Description |
1 |
*void consume() * Consumes this event so that it will not be processed in the default manner by the source which originated it. |
2 |
*int getModifiers() * Returns the modifier mask for this event. |
3 |
*int getModifiersEx() * Returns the extended modifier mask for this event. |
4 |
*static String getModifiersExText(int modifiers) * Returns a String describing the extended modifier keys and mouse buttons, such as "Shift", "Button1", or "Ctrl+Shift". |
5 |
long getWhen() Returns the timestamp of when this event occurred. |
6 |
*boolean isAltDown() * Returns whether or not the Alt modifier is down on this event. |
7 |
boolean isAltGraphDown() Returns whether or not the AltGraph modifier is down on this event. |
8 |
boolean isConsumed() Returns whether or not this event has been consumed. |
9 |
*boolean isControlDown() * Returns whether or not the Control modifier is down on this event. |
10 |
boolean isMetaDown() Returns whether or not the Meta modifier is down on this event. |
11 |
*boolean isShiftDown() * Returns whether or not the Shift modifier is down on this event. |
AWT KeyEvent Class
输入字符时会生成 Key 事件。按键事件有三种类型,它们由整数常量表示。这些按键事件如下:
On entering the character the Key event is generated.There are three types of key events which are represented by the integer constants. These key events are following
-
KEY_PRESSED
-
KEY_RELASED
-
KEY_TYPED
Class declaration
以下是 java.awt.event.KeyEvent 类的声明:
Following is the declaration for java.awt.event.KeyEvent class:
public class KeyEvent
extends InputEvent
Field
以下是 java.awt.InputEvent 类的字段:
Following are the fields for java.awt.InputEvent class:
-
*static char CHAR_UNDEFINED * --KEY_PRESSED and KEY_RELEASED events which do not map to a valid Unicode character use this for the keyChar value.
-
*static int KEY_FIRST * --The first number in the range of ids used for key events.
-
*static int KEY_LAST * --The last number in the range of ids used for key events.
-
*static int KEY_LOCATION_LEFT * --A constant indicating that the key pressed or released is in the left key location (there is more than one possible location for this key).
-
static int KEY_LOCATION_NUMPAD --A constant indicating that the key event originated on the numeric keypad or with a virtual key corresponding to the numeric keypad.
-
*static int KEY_LOCATION_RIGHT * — A constant indicating that the key pressed or released is in the right key location (there is more than one possible location for this key).
-
*static int KEY_LOCATION_STANDARD * --A constant indicating that the key pressed or released is not distinguished as the left or right version of a key, and did not originate on the numeric keypad (or did not originate with a virtual key corresponding to the numeric keypad).
-
static int KEY_LOCATION_UNKNOWN — A constant indicating that the keyLocation is indeterminate or not relevant.
-
static int KEY_PRESSED --The "key pressed" event.
-
*static int KEY_RELEASED * --The "key released" event.
-
*static int KEY_TYPED * --The "key typed" event.
-
*static int VK_1 *
-
*static int VK_2 *
-
*static int VK_3 *
-
*static int VK_4 *
-
*static int VK_5 *
-
*static int VK_6 *
-
*static int VK_7 *
-
*static int VK_8 *
-
*static int VK_9 *
-
*static int VK_A * --VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A)
-
*static int VK_ACCEPT * --Constant for the Accept or Commit function key.
-
*static int VK_ADD *
-
*static int VK_AGAIN *
-
*static int VK_ALL_CANDIDATES * --Constant for the All Candidates function key.
-
*static int VK_ALPHANUMERIC * --Constant for the Alphanumeric function key.
-
*static int VK_ALT *
-
*static int VK_ALT_GRAPH * --Constant for the AltGraph function key.
-
*static int VK_AMPERSAND *
-
*static int VK_ASTERISK *
-
*static int VK_AT * --constant for the "@" key.
-
*static int VK_B *
-
*static int VK_BACK_QUOTE *
-
*static int VK_BACK_SLASH * --Constant for the back slash key, "\"
-
*static int VK_BACK_SPACE *
-
*static int VK_BEGIN * --Constant for the Begin key.
-
*static int VK_BRACELEFT *
-
*static int VK_BRACERIGHT *
-
*static int VK_C *
-
*static int VK_CANCEL *
-
*static int VK_CAPS_LOCK *
-
*static int VK_CIRCUMFLEX * --Constant for the "^" key.
-
*static int VK_CLEAR *
-
*static int VK_CLOSE_BRACKET * --Constant for the close bracket key, "]"
-
*static int VK_CODE_INPUT * --Constant for the Code Input function key.
-
*static int VK_COLON * --Constant for the ":" key.
-
*static int VK_COMMA * --Constant for the comma key, ","
-
*static int VK_COMPOSE * --Constant for the Compose function key.
-
*static int VK_CONTEXT_MENU * --Constant for the Microsoft Windows Context Menu key.
-
*static int VK_CONTROL *
-
*static int VK_CONVERT * — Constant for the Convert function key.
-
*static int VK_COPY *
-
*static int VK_CUT *
-
*static int VK_D *
-
*static int VK_DEAD_ABOVEDOT *
-
*static int VK_DEAD_ABOVERING *
-
*static int VK_DEAD_ACUTE *
-
*static int VK_DEAD_BREVE *
-
*static int VK_DEAD_CARON *
-
*static int VK_DEAD_CEDILLA *
-
*static int VK_DEAD_CIRCUMFLEX *
-
*static int VK_DEAD_DIAERESIS *
-
*static int VK_DEAD_DOUBLEACUTE *
-
*static int VK_DEAD_GRAVE *
-
*static int VK_DEAD_IOTA *
-
*static int VK_DEAD_MACRON *
-
*static int VK_DEAD_OGONEK *
-
static int VK_DEAD_SEMIVOICED_SOUND
-
*static int VK_DEAD_TILDE *
-
*static int VK_DEAD_VOICED_SOUND *
-
*static int VK_DECIMAL *
-
*static int VK_DELETE *
-
*static int VK_DIVIDE *
-
*static int VK_DOLLAR * --Constant for the "$" key.
-
*static int VK_DOWN * — Constant for the non-numpad down arrow key.
-
*static int VK_E *
-
*static int VK_END *
-
*static int VK_ENTER *
-
*static int VK_EQUALS * --Constant for the equals key, "="
-
*static int VK_ESCAPE *
-
*static int VK_EURO_SIGN * --Constant for the Euro currency sign key.
-
*static int VK_EXCLAMATION_MARK * --Constant for the "!" key.
-
*static int VK_F *
-
*static int VK_F1 * --Constant for the F1 function key.
-
*static int VK_F10 * --Constant for the F10 function key.
-
*static int VK_F11 * --Constant for the F11 function key.
-
*static int VK_F12 * --Constant for the F12 function key.
-
*static int VK_F13 * --Constant for the F13 function key.
-
*static int VK_F14 * --Constant for the F14 function key.
-
*static int VK_F15 * --Constant for the F15 function key.
-
*static int VK_F16 * --Constant for the F16 function key.
-
*static int VK_F17 * --Constant for the F17 function key.
-
*static int VK_F18 * --Constant for the F18 function key.
-
*static int VK_F19 * --Constant for the F19 function key.
-
*static int VK_F2 * --Constant for the F2 function key.
-
*static int VK_F20 * --Constant for the F20 function key.
-
*static int VK_F21 * — Constant for the F21 function key.
-
*static int VK_F22 * --Constant for the F22 function key.
-
*static int VK_F23 * --Constant for the F23 function key.
-
*static int VK_F24 * --Constant for the F24 function key.
-
*static int VK_F3 * --Constant for the F3 function key.
-
*static int VK_F4 * --Constant for the F4 function key.
-
*static int VK_F5 * — Constant for the F5 function key.
-
*static int VK_F6 * --Constant for the F6 function key.
-
*static int VK_F7 * --Constant for the F7 function key.
-
*static int VK_F8 * --Constant for the F8 function key.
-
*static int VK_F9 * --Constant for the F9 function key.
-
*static int VK_FINAL *
-
*static int VK_FIND *
-
*static int VK_FULL_WIDTH * --Constant for the Full-Width Characters function key.
-
*static int VK_G *
-
*static int VK_GREATER *
-
*static int VK_H *
-
*static int VK_HALF_WIDTH * --Constant for the Half-Width Characters function key.
-
*static int VK_HELP *
-
*static int VK_HIRAGANA * --Constant for the Hiragana function key.
-
*static int VK_HOME *
-
*static int VK_I *
-
*static int VK_INPUT_METHOD_ON_OFF * — Constant for the input method on/off key.
-
*static int VK_INSERT *
-
*static int VK_INVERTED_EXCLAMATION_MARK * --Constant for the inverted exclamation mark key.
-
*static int VK_J *
-
*static int VK_JAPANESE_HIRAGANA * --Constant for the Japanese-Hiragana function key.
-
*static int VK_JAPANESE_KATAKANA * --Constant for the Japanese-Katakana function key.
-
*static int VK_JAPANESE_ROMAN * --Constant for the Japanese-Roman function key.
-
*static int VK_K *
-
*static int VK_KANA *
-
*static int VK_KANA_LOCK * — Constant for the locking Kana function key.
-
*static int VK_KANJI *
-
*static int VK_KATAKANA * --Constant for the Katakana function key.
-
*static int VK_KP_DOWN * — Constant for the numeric keypad down arrow key.
-
*static int VK_KP_LEFT * --Constant for the numeric keypad left arrow key.
-
*static int VK_KP_RIGHT * --Constant for the numeric keypad right arrow key.
-
*static int VK_KP_UP * --Constant for the numeric keypad up arrow key.
-
*static int VK_L *
-
*static int VK_LEFT * --Constant for the non-numpad left arrow key.
-
*static int VK_LEFT_PARENTHESIS * --Constant for the "(" key.
-
*static int VK_LESS *
-
*static int VK_M *
-
*static int VK_META *
-
*static int VK_MINUS * — Constant for the minus key, "-"
-
*static int VK_MODECHANGE *
-
*static int VK_MULTIPLY *
-
*static int VK_N *
-
*static int VK_NONCONVERT * --Constant for the Don’t Convert function key.
-
*static int VK_NUM_LOCK *
-
*static int VK_NUMBER_SIGN * --Constant for the "#" key.
-
*static int VK_NUMPAD0 *
-
*static int VK_NUMPAD1 *
-
*static int VK_NUMPAD2 *
-
*static int VK_NUMPAD3 *
-
*static int VK_NUMPAD4 *
-
*static int VK_NUMPAD5 *
-
*static int VK_NUMPAD6 *
-
*static int VK_NUMPAD7 *
-
*static int VK_NUMPAD8 *
-
*static int VK_NUMPAD9 *
-
*static int VK_O *
-
*static int VK_OPEN_BRACKET * --Constant for the open bracket key, "["
-
*static int VK_P *
-
static int VK_PAGE_DOWN
-
*static int VK_PAGE_UP *
-
*static int VK_PASTE *
-
*static int VK_PAUSE *
-
*static int VK_PERIOD * --Constant for the period key, "."
-
*static int VK_PLUS * — Constant for the "+" key.
-
*static int VK_PREVIOUS_CANDIDATE * — Constant for the Previous Candidate function key.
-
*static int VK_PRINTSCREEN *
-
*static int VK_PROPS *
-
*static int VK_Q *
-
*static int VK_QUOTE *
-
static int VK_QUOTEDBL
-
*static int VK_R *
-
*static int VK_RIGHT * — Constant for the non-numpad right arrow key.
-
*static int VK_RIGHT_PARENTHESIS * --Constant for the ")" key.
-
*static int VK_ROMAN_CHARACTERS * --Constant for the Roman Characters function key.
-
*static int VK_S *
-
*static int VK_SCROLL_LOCK *
-
*static int VK_SEMICOLON * — Constant for the semicolon key, ";"
-
*static int VK_SEPARATER * --This constant is obsolete, and is included only for backwards compatibility.
-
*static int VK_SEPARATOR * --Constant for the Numpad Separator key.
-
*static int VK_SHIFT *
-
*static int VK_SLASH * — Constant for the forward slash key, "/"
-
*static int VK_SPACE *
-
*static int VK_STOP *
-
static int VK_SUBTRACT
-
*static int VK_T *
-
*static int VK_TAB *
-
*static int VK_U *
-
*static int VK_UNDEFINED * — This value is used to indicate that the keyCode is unknown.
-
*static int VK_UNDERSCORE * --Constant for the "_" key.
-
static int VK_UNDO
-
*static int VK_UP * --Constant for the non-numpad up arrow key.
-
*static int VK_V *
-
*static int VK_W *
-
*static int VK_WINDOWS * --Constant for the Microsoft Windows "Windows" key.
-
*static int VK_X *
-
*static int VK_Y *
-
*static int VK_Z *
Class constructors
S.N. |
Constructor & Description |
1 |
*KeyEvent(Component source, int id, long when, int modifiers, int keyCode) * Deprecated. as of JDK1.1 |
2 |
*KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar) * Constructs a KeyEvent object. |
3 |
KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar, int keyLocation) |
Class methods
S.N. |
Method & Description |
1 |
*char getKeyChar() * Returns the character associated with the key in this event. |
2 |
*int getKeyCode() * Returns the integer keyCode associated with the key in this event. |
3 |
*int getKeyLocation() * Returns the location of the key that originated this key event. |
4 |
*static String getKeyModifiersText(int modifiers) * Returns a String describing the modifier key(s), such as "Shift", or "Ctrl+Shift". |
5 |
*static String getKeyText(int keyCode) * Returns a String describing the keyCode, such as "HOME", "F1" or "A". |
6 |
*boolean isActionKey() * Returns whether the key in this event is an "action" key. |
7 |
*String paramString() * Returns a parameter string identifying this event. |
8 |
*void setKeyChar(char keyChar) * Set the keyChar value to indicate a logical character. |
9 |
*void setKeyCode(int keyCode) * Set the keyCode value to indicate a physical key. |
10 |
*void setModifiers(int modifiers) * Deprecated. as of JDK1.1.4 |
AWT MouseEvent Class
该事件指示组件中发生了鼠标动作。此低级事件是由组件对象针对鼠标事件和鼠标移动事件生成的。
This event indicates a mouse action occurred in a component. This low-level event is generated by a component object for Mouse Events and Mouse motion events.
-
a mouse button is pressed
-
a mouse button is released
-
a mouse button is clicked (pressed and released)
-
a mouse cursor enters the unobscured part of component’s geometry
-
a mouse cursor exits the unobscured part of component’s geometry
-
a mouse is moved
-
the mouse is dragged
Class declaration
以下是 java.awt.event.MouseEvent 类的声明:
Following is the declaration for java.awt.event.MouseEvent class:
public class MouseEvent
extends InputEvent
Field
以下是 java.awt.event.MouseEvent 类的字段:
Following are the fields for java.awt.event.MouseEvent class:
-
*static int BUTTON1 * --Indicates mouse button #1; used by getButton()
-
*static int BUTTON2 * --Indicates mouse button #2; used by getButton()
-
*static int BUTTON3 * --Indicates mouse button #3; used by getButton()
-
*static int MOUSE_CLICKED * --The "mouse clicked" event
-
*static int MOUSE_DRAGGED * --The "mouse dragged" event
-
*static int MOUSE_ENTERED * --The "mouse entered" event
-
*static int MOUSE_EXITED * --The "mouse exited" event
-
*static int MOUSE_FIRST * --The first number in the range of ids used for mouse events
-
*static int MOUSE_LAST * — The last number in the range of ids used for mouse events
-
*static int MOUSE_MOVED * --The "mouse moved" event
-
*static int MOUSE_PRESSED * — The "mouse pressed" event
-
*static int MOUSE_RELEASED * --The "mouse released" event
-
*static int MOUSE_WHEEL * --The "mouse wheel" event
-
*static int NOBUTTON * --Indicates no mouse buttons; used by getButton()
-
*static int VK_WINDOWS * --Constant for the Microsoft Windows "Windows" key.
Class constructors
S.N. |
Constructor & Description |
1 |
*MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger) * Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count. |
2 |
*MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger, int button) * Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count. |
3 |
*MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int xAbs, int yAbs, int clickCount, boolean popupTrigger, int button) * Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, absolute coordinates, and click count. |
Class methods
S.N. |
Method & Description |
1 |
*int getButton() * Returns which, if any, of the mouse buttons has changed state. |
2 |
*int getClickCount() * Returns the number of mouse clicks associated with this event. |
3 |
*Point getLocationOnScreen() * Returns the absolute x, y position of the event. |
4 |
*static String getMouseModifiersText(int modifiers) * Returns a String describing the modifier keys and mouse buttons that were down during the event, such as "Shift", or "Ctrl+Shift". |
5 |
*Point getPoint() * Returns the x,y position of the event relative to the source component. |
6 |
*int getX() * Returns the horizontal x position of the event relative to the source component. |
7 |
*int getXOnScreen() * Returns the absolute horizontal x position of the event. |
8 |
*int getY() * Returns the vertical y position of the event relative to the source component. |
9 |
*int getYOnScreen() * Returns the absolute vertical y position of the event. |
10 |
boolean isPopupTrigger() Returns whether or not this mouse event is the popup menu trigger event for the platform. |
11 |
*String paramString() * Returns a parameter string identifying this event. |
12 |
*void translatePoint(int x, int y) * Translates the event’s coordinates to a new position by adding specified x (horizontal) and y (vertical) offsets. |
AWT TextEvent Class
这个类的对象表示文本事件。TextEvent 在文本字段或文本区域输入字符时生成。TextEvent 实例不包括在生成事件的文本组件中当前存在的字符,而是为我们提供了检索该信息的其它方法。
The object of this class represents the text events.The TextEvent is generated when character is entered in the text fields or text area. The TextEvent instance does not include the characters currently in the text component that generated the event rather we are provided with other methods to retrieve that information.
Class declaration
以下是 java.awt.event.TextEvent 类的声明:
Following is the declaration for java.awt.event.TextEvent class:
public class TextEvent
extends AWTEvent
Field
以下是 java.awt.event.TextEvent 类的字段:
Following are the fields for java.awt.event.TextEvent class:
-
*static int TEXT_FIRST * --The first number in the range of ids used for text events.
-
*static int TEXT_LAST * --The last number in the range of ids used for text events.
-
*static int TEXT_VALUE_CHANGED * --This event id indicates that object’s text changed.
Class constructors
S.N. |
Constructor & Description |
1 |
*TextEvent(Object source, int id) * Constructs a TextEvent object. |
AWT WindowEvent Class
此类的对象表示窗口状态的变化。当窗口打开、关闭、激活、停用、最小化或取消最小化,或者当焦点转移到窗口内或移出窗口外时,此低级事件由窗口对象生成。
The object of this class represents the change in state of a window.This low-level event is generated by a Window object when it is opened, closed, activated, deactivated, iconified, or deiconified, or when focus is transfered into or out of the Window.
Class declaration
以下是对 java.awt.event.WindowEvent 类的声明:
Following is the declaration for java.awt.event.WindowEvent class:
public class WindowEvent
extends ComponentEvent
Field
以下是对 java.awt.event.WindowEvent 类域的说明:
Following are the fields for java.awt.event.WindowEvent class:
-
*static int WINDOW_ACTIVATED * --The window-activated event type.
-
*static int WINDOW_CLOSED * — The window closed event.
-
*static int WINDOW_CLOSING * — The "window is closing" event.
-
*static int WINDOW_DEACTIVATED * — The window-deactivated event type.
-
*static int WINDOW_DEICONIFIED * — The window deiconified event type.
-
*static int WINDOW_FIRST * — The first number in the range of ids used for window events.
-
*static int WINDOW_GAINED_FOCUS * — The window-gained-focus event type.
-
*static int WINDOW_ICONIFIED * — The window iconified event.
-
*static int WINDOW_LAST * — The last number in the range of ids used for window events.
-
*static int WINDOW_LOST_FOCUS * — The window-lost-focus event type.
-
*static int WINDOW_OPENED * — The window opened event.
-
*static int WINDOW_STATE_CHANGED * — The window-state-changed event type.
Class constructors
S.N. |
Constructor & Description |
1 |
*WindowEvent(Window source, int id) * Constructs a WindowEvent object. |
2 |
*WindowEvent(Window source, int id, int oldState, int newState) * Constructs a WindowEvent object with the specified previous and new window states. |
3 |
*WindowEvent(Window source, int id, Window opposite) * Constructs a WindowEvent object with the specified opposite Window. |
4 |
*WindowEvent(Window source, int id, Window opposite, int oldState, int newState) * Constructs a WindowEvent object. |
Class methods
S.N. |
Method & Description |
1 |
*int getNewState() * For WINDOW_STATE_CHANGED events returns the new state of the window. |
2 |
*int getOldState() * For WINDOW_STATE_CHANGED events returns the previous state of the window. |
3 |
*Window getOppositeWindow() * Returns the other Window involved in this focus or activation change. |
4 |
*Window getWindow() * Returns the originator of the event. |
5 |
*String paramString() * Returns a parameter string identifying this event. |
AWT AdjustmentEvent Class
Introduction
类 AdjustmentEvent 表示可调整对象发出的调整事件。
The Class AdjustmentEvent represents adjustment event emitted by Adjustable objects.
Class declaration
以下是 java.awt.event.AdjustmentEvent 类的声明:
Following is the declaration for java.awt.event.AdjustmentEvent class:
public class AdjustmentEvent
extends AWTEvent
Field
以下是 java.awt.Component 类的字段:
Following are the fields for java.awt.Component class:
-
*static int ADJUSTMENT_FIRST * — Marks the first integer id for the range of adjustment event ids.
-
*static int ADJUSTMENT_LAST * — Marks the last integer id for the range of adjustment event ids.
-
*static int ADJUSTMENT_VALUE_CHANGED * — The adjustment value changed event.
-
*static int BLOCK_DECREMENT * — The block decrement adjustment type.
-
*static int BLOCK_INCREMENT * — The block increment adjustment type.
-
*static int TRACK * — The absolute tracking adjustment type.
-
*static int UNIT_DECREMENT * — The unit decrement adjustment type.
-
*static int UNIT_INCREMENT * — The unit increment adjustment type.
Class constructors
S.N. |
Constructor & Description |
1 |
*AdjustmentEvent(Adjustable source, int id, int type, int value) * Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value. |
2 |
*AdjustmentEvent(Adjustable source, int id, int type, int value, boolean isAdjusting) * Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value. |
Class methods
S.N. |
Method & Description |
1 |
*Adjustable getAdjustable() * Returns the Adjustable object where this event originated. |
2 |
*int getAdjustmentType() * Returns the type of adjustment which caused the value changed event. |
3 |
*int getValue() * Returns the current value in the adjustment event. |
4 |
*boolean getValueIsAdjusting() * Returns true if this is one of multiple adjustment events. |
5 |
*String paramString() * Returns a string representing the state of this Event. |
AWT ComponentEvent Class
Introduction
类 ComponentEvent 表示组件移动、调整大小或更改可见性
The Class ComponentEvent represents that a component moved, changed size, or changed visibility
Class declaration
以下是 java.awt.event.ComponentEvent 类的声明:
Following is the declaration for java.awt.event.ComponentEvent class:
public class ComponentEvent
extends AWTEvent
Field
以下是 java.awt.Component 类的字段:
Following are the fields for java.awt.Component class:
-
*static int COMPONENT_FIRST * — The first number in the range of ids used for component events.
-
*static int COMPONENT_HIDDEN * --This event indicates that the component was rendered invisible.
-
*static int COMPONENT_LAST * — The last number in the range of ids used for component events.
-
*static int COMPONENT_MOVED * — This event indicates that the component’s position changed.
-
*static int COMPONENT_RESIZED * — This event indicates that the component’s size changed.
-
*static int COMPONENT_SHOWN * — This event indicates that the component was made visible.
Class constructors
S.N. |
Constructor & Description |
1 |
*ComponentEvent(Component source, int id) * Constructs a ComponentEvent object. |
AWT ContainerEvent Class
Introduction
类 ContainerEvent 表示容器的内容由于组件的添加或移除而发生更改。
The Class ContainerEvent represents that a container’s contents changed because a component was added or removed.
Class declaration
以下为 java.awt.event.ContainerEvent 类声明:
Following is the declaration for java.awt.event.ContainerEvent class:
public class ContainerEvent
extends ComponentEvent
Field
以下是 java.awt.Component 类的字段:
Following are the fields for java.awt.Component class:
-
*static int COMPONENT_ADDED * — This event indicates that a component was added to the container.
-
*static int COMPONENT_REMOVED * — This event indicates that a component was removed from the container.
-
*static int CONTAINER_FIRST * — The first number in the range of ids used for container events.
-
*static int CONTAINER_LAST * — The last number in the range of ids used for container events.
Class constructors
S.N. |
Constructor & Description |
1 |
*ContainerEvent(Component source, int id, Component child) * Constructs a ContainerEvent object. |
AWT MouseMotionEvent Class
Introduction
接口 MouseMotionEvent 表示组件中发生了鼠标操作。此底层事件由在鼠标被拖动或移动时生成的组件对象生成。
The interface MouseMotionEvent indicates a mouse action occurred in a component. This low-level event is generated by a component object when mouse is dragged or moved.
Class declaration
以下为 java.awt.event.MouseMotionEvent 类的声明:
Following is the declaration for java.awt.event.MouseMotionEvent Class:
public class MouseMotionEvent
extends InputEvent
AWT PaintEvent Class
Introduction
类 PaintEvent 用于确保 paint/update 方法调用与从事件队列中传递的其他事件一起序列化。
The Class PaintEvent used to ensure that paint/update method calls are serialized along with the other events delivered from the event queue
Class declaration
以下为 java.awt.event.PaintEvent 类的声明:
Following is the declaration for java.awt.event.PaintEvent class:
public class PaintEvent
extends ComponentEvent
Field
以下是 java.awt.Component 类的字段:
Following are the fields for java.awt.Component class:
-
*static int PAINT * — The paint event type.
-
*static int PAINT_FIRST * — Marks the first integer id for the range of paint event ids.
-
*static int PAINT_LAST * — Marks the last integer id for the range of paint event ids.
-
*static int UPDATE * — The update event type.
Class constructors
S.N. |
Constructor & Description |
1 |
PaintEvent(Component source, int id, Rectangle updateRect) Constructs a PaintEvent object with the specified source component and type. |
Class methods
S.N. |
Method & Description |
1 |
*Rectangle getUpdateRect() * Returns the rectangle representing the area which needs to be repainted in response to this event. |
2 |
String paramString() Returns a parameter string identifying this event. |
3 |
*void setUpdateRect(Rectangle updateRect) * Sets the rectangle representing the area which needs to be repainted in response to this event. |
AWT Event Listeners
事件侦听器表示负责处理事件的接口。Java 为我们提供了各种事件侦听器类,但我们将讨论那些最常使用的类。每个事件侦听器方法都有一个参数,该参数作为 EventObject 类的子类的对象。例如,鼠标事件侦听器方法将接受 MouseEvent 的实例,而 MouseEvent 派生自 EventObject。
The Event listener represent the interfaces responsible to handle events. Java provides us various Event listener classes but we will discuss those which are more frequently used. Every method of an event listener method has a single argument as an object which is subclass of EventObject class. For example, mouse event listener methods will accept instance of MouseEvent, where MouseEvent derives from EventObject.
EventListner interface
这是一个标记接口,每个侦听器接口都必须对其进行扩展。此类在 java.util 包中定义。
It is a marker interface which every listener interface has to extend.This class is defined in java.util package.
AWT ActionListener Interface
处理 ActionEvent 的类应该实现此接口。该类的对象必须在组件中注册。可以使用 addActionListener() 方法注册对象。当发生动作事件时,将调用该对象的 actionPerformed 方法。
The class which processes the ActionEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addActionListener() method. When the action event occurs, that object’s actionPerformed method is invoked.
Interface declaration
以下是 java.awt.event.ActionListener 接口的声明:
Following is the declaration for java.awt.event.ActionListener interface:
public interface ActionListener
extends EventListener
Interface methods
S.N. |
Method & Description |
1 |
*void actionPerformed(ActionEvent e) * Invoked when an action occurs. |
Methods inherited
此接口从以下接口继承方法:
This interface inherits methods from the following interfaces:
-
java.awt.EventListener
ActionListener Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtListenerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtListenerDemo awtListenerDemo = new AwtListenerDemo();
awtListenerDemo.showActionListenerDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showActionListenerDemo(){
headerLabel.setText("Listener in action: ActionListener");
ScrollPane panel = new ScrollPane();
panel.setBackground(Color.magenta);
Button okButton = new Button("OK");
okButton.addActionListener(new CustomActionListener());
panel.add(okButton);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
class CustomActionListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Ok Button Clicked.");
}
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo
验证以下输出
Verify the following output
AWT ComponentListener Interface
处理 ComponentEvent 的类应该实现此接口。该类的对象必须在组件中注册。可以使用 addComponentListener() 方法注册对象。组件事件仅用于提供信息。
The class which processes the ComponentEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addComponentListener() method. Component event are raised for information only.
Interface declaration
以下是 java.awt.event.ComponentListener 接口的声明:
Following is the declaration for java.awt.event.ComponentListener interface:
public interface ComponentListener
extends EventListener
Interface methods
S.N. |
Method & Description |
1 |
*void componentHidden(ComponentEvent e) * Invoked when the component has been made invisible. |
2 |
*void componentMoved(ComponentEvent e) * Invoked when the component’s position changes. |
3 |
*void componentResized(ComponentEvent e) * Invoked when the component’s size changes. |
4 |
*void componentShown(ComponentEvent e) * Invoked when the component has been made visible. |
Methods inherited
此接口从以下接口继承方法:
This interface inherits methods from the following interfaces:
-
java.awt.EventListener
ComponentListener Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtListenerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtListenerDemo awtListenerDemo = new AwtListenerDemo();
awtListenerDemo.showComponentListenerDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showComponentListenerDemo(){
headerLabel.setText("Listener in action: ComponentListener");
ScrollPane panel = new ScrollPane();
panel.setBackground(Color.magenta);
Label msglabel = new Label();
msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
panel.add(msglabel);
msglabel.addComponentListener(new CustomComponentListener());
controlPanel.add(panel);
mainFrame.setVisible(true);
}
class CustomComponentListener implements ComponentListener {
public void componentResized(ComponentEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName() + " resized. ");
}
public void componentMoved(ComponentEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName() + " moved. ");
}
public void componentShown(ComponentEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName() + " shown. ");
}
public void componentHidden(ComponentEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName() + " hidden. ");
}
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo
验证以下输出
Verify the following output
AWT ItemListener Interface
处理 ItemEvent 的类应该实现此接口。该类的对象必须在组件中注册。可以使用 addItemListener() 方法注册对象。当动作事件发生时,将调用该对象的 itemStateChanged 方法。
The class which processes the ItemEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addItemListener() method. When the action event occurs, that object’s itemStateChanged method is invoked.
Interface declaration
以下是 java.awt.event.ItemListener 接口的声明:
Following is the declaration for java.awt.event.ItemListener interface:
public interface ItemListener
extends EventListener
Interface methods
S.N. |
Method & Description |
1 |
*void itemStateChanged(ItemEvent e) * Invoked when an item has been selected or deselected by the user. |
Methods inherited
此接口从以下接口继承方法:
This interface inherits methods from the following interfaces:
-
java.awt.EventListener
ItemListener Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtListenerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtListenerDemo awtListenerDemo = new AwtListenerDemo();
awtListenerDemo.showItemListenerDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showItemListenerDemo(){
headerLabel.setText("Listener in action: ItemListener");
Checkbox chkApple = new Checkbox("Apple");
Checkbox chkMango = new Checkbox("Mango");
Checkbox chkPeer = new Checkbox("Peer");
chkApple.addItemListener(new CustomItemListener());
chkMango.addItemListener(new CustomItemListener());
chkPeer.addItemListener(new CustomItemListener());
controlPanel.add(chkApple);
controlPanel.add(chkMango);
controlPanel.add(chkPeer);
mainFrame.setVisible(true);
}
class CustomItemListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText(e.getItem()
+" Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo
验证以下输出
Verify the following output
AWT KeyListener Interface
处理 KeyEvent 的类应实现此接口,该类的对象必须用组件注册。可以使用 addKeyListener() 方法注册该对象。
The class which processes the KeyEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addKeyListener() method.
Interface declaration
下面是 java.awt.event.KeyListener 接口的声明:
Following is the declaration for java.awt.event.KeyListener interface:
public interface KeyListener
extends EventListener
Interface methods
S.N. |
Method & Description |
1 |
*void keyPressed(KeyEvent e) * Invoked when a key has been pressed. |
2 |
*void keyReleased(KeyEvent e) * Invoked when a key has been released. |
3 |
*void keyTyped(KeyEvent e) * Invoked when a key has been typed. |
Methods inherited
此接口从以下接口继承方法:
This interface inherits methods from the following interfaces:
-
java.awt.EventListener
KeyListener Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtListenerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
private TextField textField;
public AwtListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtListenerDemo awtListenerDemo = new AwtListenerDemo();
awtListenerDemo.showKeyListenerDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showKeyListenerDemo(){
headerLabel.setText("Listener in action: KeyListener");
textField = new TextField(10);
textField.addKeyListener(new CustomKeyListener());
Button okButton = new Button("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Entered text: " + textField.getText());
}
});
controlPanel.add(textField);
controlPanel.add(okButton);
mainFrame.setVisible(true);
}
class CustomKeyListener implements KeyListener{
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
statusLabel.setText("Entered text: " + textField.getText());
}
}
public void keyReleased(KeyEvent e) {
}
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo
验证以下输出
Verify the following output
AWT MouseListener Interface
处理 MouseEvent 的类应实现此接口,该类的对象必须用组件注册。可以使用 addMouseListener() 方法注册该对象。
The class which processes the MouseEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addMouseListener() method.
Interface declaration
下面是 java.awt.event.MouseListener 接口的声明:
Following is the declaration for java.awt.event.MouseListener interface:
public interface MouseListener
extends EventListener
Interface methods
S.N. |
Method & Description |
1 |
*void mouseClicked(MouseEvent e) * Invoked when the mouse button has been clicked (pressed and released) on a component. |
2 |
*void mouseEntered(MouseEvent e) * Invoked when the mouse enters a component. |
3 |
*void mouseExited(MouseEvent e) * Invoked when the mouse exits a component. |
4 |
*void mousePressed(MouseEvent e) * Invoked when a mouse button has been pressed on a component. |
5 |
void mouseReleased(MouseEvent e) Invoked when a mouse button has been released on a component. |
Methods inherited
此接口从以下接口继承方法:
This interface inherits methods from the following interfaces:
-
java.awt.EventListener
MouseListener Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtListenerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtListenerDemo awtListenerDemo = new AwtListenerDemo();
awtListenerDemo.showMouseListenerDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showMouseListenerDemo(){
headerLabel.setText("Listener in action: MouseListener");
Panel panel = new Panel();
panel.setBackground(Color.magenta);
panel.setLayout(new FlowLayout());
panel.addMouseListener(new CustomMouseListener());
Label msglabel = new Label();
msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
msglabel.addMouseListener(new CustomMouseListener());
panel.add(msglabel);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
class CustomMouseListener implements MouseListener{
public void mouseClicked(MouseEvent e) {
statusLabel.setText("Mouse Clicked: ("
+e.getX()+", "+e.getY() +")");
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo
验证以下输出
Verify the following output
AWT TextListener Interface
处理 TextEvent 的类应实现此接口,该类的对象必须用组件注册。可以使用 addTextListener() 方法注册该对象。
The class which processes the TextEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addTextListener() method.
Interface declaration
下面是 java.awt.event.TextListener 接口的声明:
Following is the declaration for java.awt.event.TextListener interface:
public interface TextListener
extends EventListener
Interface methods
S.N. |
Method & Description |
1 |
*void textValueChanged(TextEvent e) * Invoked when the value of the text has changed. |
Methods inherited
此接口从以下接口继承方法:
This interface inherits methods from the following interfaces:
-
java.awt.EventListener
TextListener Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtListenerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
private TextField textField;
public AwtListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtListenerDemo awtListenerDemo = new AwtListenerDemo();
awtListenerDemo.showTextListenerDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showTextListenerDemo(){
headerLabel.setText("Listener in action: TextListener");
textField = new TextField(10);
textField.addTextListener(new CustomTextListener());
Button okButton = new Button("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Entered text: "
+ textField.getText());
}
});
controlPanel.add(textField);
controlPanel.add(okButton);
mainFrame.setVisible(true);
}
class CustomTextListener implements TextListener {
public void textValueChanged(TextEvent e) {
statusLabel.setText("Entered text: " + textField.getText());
}
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo
验证以下输出
Verify the following output
AWT WindowListener Interface
处理 WindowEvent 的类应实现此接口,该类的对象必须用组件注册。可以使用 addWindowListener() 方法注册该对象。
The class which processes the WindowEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addWindowListener() method.
Interface declaration
下面是 java.awt.event.WindowListener 接口的声明:
Following is the declaration for java.awt.event.WindowListener interface:
public interface WindowListener
extends EventListener
Interface methods
S.N. |
Method & Description |
1 |
*void windowActivated(WindowEvent e) * Invoked when the Window is set to be the active Window. |
2 |
*void windowClosed(WindowEvent e) * Invoked when a window has been closed as the result of calling dispose on the window. |
3 |
*void windowClosing(WindowEvent e) * Invoked when the user attempts to close the window from the window’s system menu. |
4 |
*void windowDeactivated(WindowEvent e) * Invoked when a Window is no longer the active Window. |
5 |
*void windowDeiconified(WindowEvent e) * Invoked when a window is changed from a minimized to a normal state. |
6 |
*void windowIconified(WindowEvent e) * Invoked when a window is changed from a normal to a minimized state. |
7 |
*void windowOpened(WindowEvent e) * Invoked the first time a window is made visible. |
Methods inherited
此接口从以下接口继承方法:
This interface inherits methods from the following interfaces:
-
java.awt.EventListener
WindowListener Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtListenerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtListenerDemo awtListenerDemo = new AwtListenerDemo();
awtListenerDemo.showWindowListenerDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showWindowListenerDemo(){
headerLabel.setText("Listener in action: WindowListener");
Button okButton = new Button("OK");
aboutFrame = new Frame();
aboutFrame.setSize(300,200);;
aboutFrame.setTitle("WindowListener Demo");
aboutFrame.addWindowListener(new CustomWindowListener());
Label msgLabel = new Label("Welcome to tutorialspoint.");
msgLabel.setAlignment(Label.CENTER);
msgLabel.setSize(100,100);
aboutFrame.add(msgLabel);
aboutFrame.setVisible(true);
}
class CustomWindowListener implements WindowListener {
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
aboutFrame.dispose();
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo
验证以下输出
Verify the following output
AWT AdjustmentListener Interface
Introduction
接口*AdjustmentListener*用于接收调整事件。处理调整事件的类需要实现此接口。
The interface*AdjustmentListener* is used for receiving adjustment events. The class that process adjustment events needs to implements this interface.
Class declaration
以下是 java.awt.event.AdjustmentListener 接口的声明:
Following is the declaration for java.awt.event.AdjustmentListener interface:
public interface AdjustmentListener
extends EventListener
Interface methods
S.N. |
Method & Description |
1 |
*void adjustmentValueChanged(AdjustmentEvent e) * Invoked when the value of the adjustable has changed. |
Methods inherited
此类从以下接口继承方法:
This class inherits methods from the following interfaces:
-
java.awt.event.EventListener
AdjustmentListener Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtListenerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtListenerDemo awtListenerDemo = new AwtListenerDemo();
awtListenerDemo.showAdjustmentListenerDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showAdjustmentListenerDemo(){
headerLabel.setText("Listener in action: AdjustmentListener");
ScrollPane panel = new ScrollPane();
panel.setBackground(Color.magenta);
panel.getHAdjustable().addAdjustmentListener(new CustomAdjustmentListener());
Label msglabel = new Label();
msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
panel.add(msglabel);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
class CustomAdjustmentListener implements AdjustmentListener {
public void adjustmentValueChanged(AdjustmentEvent e) {
statusLabel.setText("Adjustment value: "+Integer.toString(e.getValue()));
}
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo
验证以下输出
Verify the following output
AWT ContainerListener Interface
Introduction
接口*ContainerListener*用于接收容器事件。处理容器事件的类需要实现此接口。
The interface*ContainerListener* is used for receiving container events. The class that process container events needs to implements this interface.
Class declaration
以下是 java.awt.event.ContainerListener 接口的声明:
Following is the declaration for java.awt.event.ContainerListener interface:
public interface ContainerListener
extends EventListener
Interface methods
S.N. |
Method & Description |
1 |
*void componentAdded(ContainerEvent e) * Invoked when a component has been added to the container. |
2 |
*void componentRemoved(ContainerEvent e) * Invoked when a component has been removed from the container. |
Methods inherited
此类从以下接口继承方法:
This class inherits methods from the following interfaces:
-
java.awt.event.EventListener
AdjustmentListener Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtListenerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtListenerDemo awtListenerDemo = new AwtListenerDemo();
awtListenerDemo.showContainerListenerDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showContainerListenerDemo(){
headerLabel.setText("Listener in action: ContainerListener");
ScrollPane panel = new ScrollPane();
panel.setBackground(Color.magenta);
panel.addContainerListener(new CustomContainerListener());
Label msglabel = new Label();
msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
panel.add(msglabel);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
class CustomContainerListener implements ContainerListener {
public void componentAdded(ContainerEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName() + " added. ");
}
public void componentRemoved(ContainerEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName() + " removed. ");
}
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo
验证以下输出
Verify the following output
AWT MouseMotionListener Interface
Introduction
接口*MouseMotionListener*用于接收组件上的鼠标移动事件。处理鼠标移动事件的类需要实现此接口。
The interface*MouseMotionListener* is used for receiving mouse motion events on a component. The class that process mouse motion events needs to implements this interface.
Class declaration
以下是 java.awt.event.MouseMotionListener 接口的声明:
Following is the declaration for java.awt.event.MouseMotionListener interface:
public interface MouseMotionListener
extends EventListener
Interface methods
S.N. |
Method & Description |
1 |
void mouseDragged(MouseEvent e) Invoked when a mouse button is pressed on a component and then dragged. |
2 |
void mouseMoved(MouseEvent e) Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed. |
Methods inherited
此类从以下接口继承方法:
This class inherits methods from the following interfaces:
-
java.awt.event.EventListener
MouseMotionListener Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtListenerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtListenerDemo awtListenerDemo = new AwtListenerDemo();
awtListenerDemo.showMouseMotionListenerDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showMouseMotionListenerDemo(){
headerLabel.setText("Listener in action: MouseMotionListener");
Panel panel = new Panel();
panel.setBackground(Color.magenta);
panel.setLayout(new FlowLayout());
panel.addMouseMotionListener(new CustomMouseMotionListener());
Label msglabel = new Label();
msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
panel.add(msglabel);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
class CustomMouseMotionListener implements MouseMotionListener {
public void mouseDragged(MouseEvent e) {
statusLabel.setText("Mouse Dragged: ("+e.getX()+", "+e.getY() +")");
}
public void mouseMoved(MouseEvent e) {
statusLabel.setText("Mouse Moved: ("+e.getX()+", "+e.getY() +")");
}
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo
验证以下输出
Verify the following output
AWT FocusListener Interface
Introduction
接口*FocusListener*用于接收键盘焦点事件。处理焦点事件的类需要实现此接口。
The interface*FocusListener* is used for receiving keyboard focus events. The class that process focus events needs to implements this interface.
Class declaration
以下是 java.awt.event.FocusListener 接口的声明:
Following is the declaration for java.awt.event.FocusListener interface:
public interface FocusListener
extends EventListener
Interface methods
S.N. |
Method & Description |
1 |
void focusGained(FocusEvent e) Invoked when a component gains the keyboard focus. |
2 |
void focusLost(FocusEvent e) Invoked when a component loses the keyboard focus. |
Methods inherited
此类从以下接口继承方法:
This class inherits methods from the following interfaces:
-
java.awt.event.EventListener
FocusListener Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtListenerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtListenerDemo awtListenerDemo = new AwtListenerDemo();
awtListenerDemo.showFocusListenerDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showFocusListenerDemo(){
headerLabel.setText("Listener in action: FocusListener");
Button okButton = new Button("OK");
Button cancelButton = new Button("Cancel");
okButton.addFocusListener(new CustomFocusListener());
cancelButton.addFocusListener(new CustomFocusListener());
controlPanel.add(okButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
class CustomFocusListener implements FocusListener{
public void focusGained(FocusEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName() + " gained focus. ");
}
public void focusLost(FocusEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName() + " lost focus. ");
}
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo
验证以下输出
Verify the following output
AWT Event Adapters
适配器是用来接收各种事件的抽象类。这些类中的方法是空的。这些类存在是为了方便创建侦听器对象。
Adapters are abstract classes for receiving various events. The methods in these classes are empty. These classes exists as convenience for creating listener objects.
AWT FocusAdapter Class
Introduction
类 FocusAdapter 是用于接收键盘焦点事件的抽象(适配器)类。此类的所有方法均为空。此类是用于创建监听器对象的便捷类。
The class FocusAdapter is an abstract (adapter) class for receiving keyboard focus events. All methods of this class are empty. This class is convenience class for creating listener objects.
Class declaration
以下是 java.awt.event.FocusAdapter 类的声明:
Following is the declaration for java.awt.event.FocusAdapter class:
public abstract class FocusAdapter
extends Object
implements FocusListener
Class methods
S.N. |
Method & Description |
1 |
*void focusGained(FocusEvent e) * Invoked when a component gains the keyboard focus. |
2 |
*focusLost(FocusEvent e) * Invoked when a component loses the keyboard focus. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.lang.Object
FocusAdapter Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtAdapterDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtAdapterDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtAdapterDemo awtAdapterDemo = new AwtAdapterDemo();
awtAdapterDemo.showFocusAdapterDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showFocusAdapterDemo(){
headerLabel.setText("Listener in action: FocusAdapter");
Button okButton = new Button("OK");
Button cancelButton = new Button("Cancel");
okButton.addFocusListener(new FocusAdapter(){
public void focusGained(FocusEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName()
+ " gained focus. ");
}
});
cancelButton.addFocusListener(new FocusAdapter(){
public void focusLost(FocusEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName()
+ " lost focus. ");
}
});
controlPanel.add(okButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo
验证以下输出
Verify the following output
AWT KeyAdapter Class
Introduction
类 KeyAdapter 是用于接收键盘事件的抽象(适配器)类。此类的所有方法均为空。此类是用于创建监听器对象的便捷类。
The class KeyAdapter is an abstract (adapter) class for receiving keyboard events. All methods of this class are empty. This class is convenience class for creating listener objects.
Class declaration
以下是 java.awt.event.KeyAdapter 类的声明:
Following is the declaration for java.awt.event.KeyAdapter class:
public abstract class KeyAdapter
extends Object
implements KeyListener
Class methods
S.N. |
Method & Description |
1 |
*void keyPressed(KeyEvent e) * Invoked when a key has been pressed. |
2 |
*void keyReleased(KeyEvent e) * Invoked when a key has been released. |
3 |
*void keyTyped(KeyEvent e) * Invoked when a key has been typed. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.lang.Object
KeyAdapter Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtAdapterDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtAdapterDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtAdapterDemo awtAdapterDemo = new AwtAdapterDemo();
awtAdapterDemo.showKeyAdapterDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showKeyAdapterDemo(){
headerLabel.setText("Listener in action: KeyAdapter");
final TextField textField = new TextField(10);
textField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
statusLabel.setText("Entered text: " + textField.getText());
}
}
});
Button okButton = new Button("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Entered text: " + textField.getText());
}
});
controlPanel.add(textField);
controlPanel.add(okButton);
mainFrame.setVisible(true);
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo
验证以下输出
Verify the following output
AWT MouseAdapter Class
Introduction
类 MouseAdapter 是用于接收鼠标事件的抽象(适配器)类。此类的所有方法均为空。此类是用于创建监听器对象的便捷类。
The class MouseAdapter is an abstract (adapter) class for receiving mouse events. All methods of this class are empty. This class is convenience class for creating listener objects.
Class declaration
以下是 java.awt.event.MouseAdapter 类的声明:
Following is the declaration for java.awt.event.MouseAdapter class:
public abstract class MouseAdapter
extends Object
implements MouseListener, MouseWheelListener, MouseMotionListener
Class methods
S.N. |
Method & Description |
1 |
*void mouseClicked(MouseEvent e) * Invoked when the mouse button has been clicked (pressed and released) on a component. |
2 |
*void mouseDragged(MouseEvent e) * Invoked when a mouse button is pressed on a component and then dragged. |
3 |
*void mouseEntered(MouseEvent e) * Invoked when the mouse enters a component. |
4 |
*void mouseExited(MouseEvent e) * Invoked when the mouse exits a component. |
5 |
*void mouseMoved(MouseEvent e) * Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed. |
6 |
*void mousePressed(MouseEvent e) * Invoked when a mouse button has been pressed on a component. |
7 |
*void mouseReleased(MouseEvent e) * Invoked when a mouse button has been released on a component. |
8 |
*void mouseWheelMoved(MouseWheelEvent e) * Invoked when the mouse wheel is rotated. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.lang.Object
MouseAdapter Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtAdapterDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtAdapterDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtAdapterDemo awtAdapterDemo = new AwtAdapterDemo();
awtAdapterDemo.showMouseAdapterDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showMouseAdapterDemo(){
headerLabel.setText("Listener in action: MouseAdapter");
Panel panel = new Panel();
panel.setBackground(Color.magenta);
panel.setLayout(new FlowLayout());
panel.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
statusLabel.setText("Mouse Clicked: ("
+e.getX()+", "+e.getY() +")");
}
});
Label msglabel = new Label();
msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
msglabel.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
statusLabel.setText("Mouse Clicked: ("
+e.getX()+", "+e.getY() +")");
}
});
panel.add(msglabel);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo
验证以下输出
Verify the following output
AWT MouseMotionAdapter Class
Introduction
类 MouseMotionAdapter 是用于接收鼠标运动事件的抽象(适配器)类。此类的所有方法均为空。此类是用于创建监听器对象的便捷类。
The class MouseMotionAdapter is an abstract (adapter) class for receiving mouse motion events. All methods of this class are empty. This class is convenience class for creating listener objects.
Class declaration
以下是 java.awt.event.MouseMotionAdapter 类的声明:
Following is the declaration for java.awt.event.MouseMotionAdapter class:
public abstract class MouseMotionAdapter
extends Object
implements MouseMotionListener
Class methods
S.N. |
Method & Description |
1 |
*void mouseDragged(MouseEvent e) * Invoked when a mouse button is pressed on a component and then dragged. |
2 |
*void mouseMoved(MouseEvent e) * Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.lang.Object
MouseMotionAdapter Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtAdapterDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtAdapterDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtAdapterDemo awtAdapterDemo = new AwtAdapterDemo();
awtAdapterDemo.showMouseMotionAdapterDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showMouseMotionAdapterDemo(){
headerLabel.setText("Listener in action: MouseMotionAdapter");
Panel panel = new Panel();
panel.setBackground(Color.magenta);
panel.setLayout(new FlowLayout());
panel.addMouseMotionListener(new MouseMotionAdapter(){
public void mouseMoved(MouseEvent e) {
statusLabel.setText("Mouse Moved: ("+e.getX()+", "+e.getY() +")");
}
});
Label msglabel = new Label();
msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
panel.add(msglabel);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo
验证以下输出
Verify the following output
AWT WindowAdapter Class
Introduction
类 WindowAdapter 是用于接收窗口事件的抽象(适配器)类。此类的所有方法均为空。此类是用于创建监听器对象的便捷类。
The class WindowAdapter is an abstract (adapter) class for receiving window events. All methods of this class are empty. This class is convenience class for creating listener objects.
Class declaration
以下是 java.awt.event.WindowAdapter 类的声明:
Following is the declaration for java.awt.event.WindowAdapter class:
public abstract class WindowAdapter
extends Object
implements WindowListener, WindowStateListener, WindowFocusListener
Class methods
S.N. |
Method & Description |
1 |
*void windowActivated(WindowEvent e) * Invoked when a window is activated. |
2 |
*void windowClosed(WindowEvent e) * Invoked when a window has been closed. |
3 |
*void windowClosing(WindowEvent e) * Invoked when a window is in the process of being closed. |
4 |
*void windowDeactivated(WindowEvent e) * Invoked when a window is de-activated. |
5 |
*void windowDeiconified(WindowEvent e) * Invoked when a window is de-iconified. |
6 |
*void windowGainedFocus(WindowEvent e) * Invoked when the Window is set to be the focused Window, which means that the Window, or one of its subcomponents, will receive keyboard events. |
7 |
*void windowIconified(WindowEvent e) * Invoked when a window is iconified. |
8 |
*void windowLostFocus(WindowEvent e) * Invoked when the Window is no longer the focused Window, which means that keyboard events will no longer be delivered to the Window or any of its subcomponents. |
9 |
*void windowOpened(WindowEvent e) * Invoked when a window has been opened. |
10 |
*void windowStateChanged(WindowEvent e) * Invoked when a window state is changed. |
Methods inherited
该类继承以下类的各种方法:
This class inherits methods from the following classes:
-
java.lang.Object
WindowAdapter Example
使用你选择的任意编辑器在给定的 D:/ > AWT > com > tutorialspoint > gui > 中创建以下 Java 程序
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtAdapterDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtAdapterDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtAdapterDemo awtAdapterDemo = new AwtAdapterDemo();
awtAdapterDemo.showWindowAdapterDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showWindowAdapterDemo(){
headerLabel.setText("Listener in action: WindowAdapter");
Button okButton = new Button("OK");
final Frame aboutFrame = new Frame();
aboutFrame.setSize(300,200);;
aboutFrame.setTitle("WindowAdapter Demo");
aboutFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
aboutFrame.dispose();
}
});
Label msgLabel = new Label("Welcome to tutorialspoint.");
msgLabel.setAlignment(Label.CENTER);
msgLabel.setSize(100,100);
aboutFrame.add(msgLabel);
aboutFrame.setVisible(true);
}
}
使用命令提示符编译该程序。转到 *D:/ > AWT * 并键入以下命令。
Compile the program using command prompt. Go to *D:/ > AWT * and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java
如果没有错误,则表示编译成功。使用以下命令运行该程序。
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo
验证以下输出
Verify the following output
AWT Layouts
Introduction
布局是指容器中组件的排列方式。换句话说,就是将组件放置在容器内的特定位置。布局管理器会自动完成布局控件的任务。
Layout means the arrangement of components within the container. In other way we can say that placing the components at a particular position within the container. The task of layouting the controls is done automatically by the Layout Manager.
Layout Manager
布局管理器会自动定位容器内的所有控件。即使我们不使用布局管理器,控件也会由默认布局管理器进行定位。可以手动布局控件,但是由于以下两个原因,这样做非常困难。
The layout manager automatically positions all the components within the container. If we do not use layout manager then also the components are positioned by the default layout manager. It is possible to layout the controls by hand but it becomes very difficult because of the following two reasons.
-
It is very tedious to handle a large number of controls within the container.
-
Oftenly the width and height information of a component is not given when we need to arrange them.
Java 为我们提供了各种布局管理器来定位控件。各种布局管理器的特性(如大小、形状和布局方式)各不相同。当小程序或应用程序窗口的大小改变时,组件的大小、形状和布局方式也会做出响应相应的改变,即布局管理器适应小程序查看器或应用程序窗口的尺寸。
Java provide us with various layout manager to position the controls. The properties like size,shape and arrangement varies from one layout manager to other layout manager. When the size of the applet or the application window changes the size, shape and arrangement of the components also changes in response i.e. the layout managers adapt to the dimensions of appletviewer or the application window.
布局管理器与容器对象相关联。每个布局管理器都是实现 LayoutManager 接口的类的对象。
The layout manager is associated with every Container object. Each layout manager is an object of the class that implements the LayoutManager interface.
以下是定义布局管理器功能的接口和类。
Following are the interfaces and classes defining functionalities of Layout Managers.
AWT LayoutManager Interface
Introduction
接口 LayoutManager 用于定义了解如何布局容器的类的接口。
The interface*LayoutManager* is used to define the interface for classes that know how to lay out Containers.
Class declaration
下面是 java.awt.LayoutManager 接口的声明:
Following is the declaration for java.awt.LayoutManager interface:
public interface LayoutManager
Interface methods
S.N. |
Method & Description |
1 |
*void addLayoutComponent(String name, Component comp) * If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name. |
2 |
*void layoutContainer(Container parent) * Lays out the specified container. |
3 |
*Dimension minimumLayoutSize(Container parent) * Calculates the minimum size dimensions for the specified container, given the components it contains. |
4 |
*Dimension preferredLayoutSize(Container parent) * Calculates the preferred size dimensions for the specified container, given the components it contains. |
5 |
*void removeLayoutComponent(Component comp) * Removes the specified component from the layout. |
AWT LayoutManager2 Interface
Introduction
接口*LayoutManger*用于定义如何根据布局约束对象布局容器的类的接口。
The interface*LayoutManger* is used to define the interface for classes that know how to lay out Containers based on a layout constraints object.
Class declaration
以下为 java.awt.LayoutManager2 接口的声明:
Following is the declaration for java.awt.LayoutManager2 interface:
public interface LayoutManger2
extends LayoutManager
Interface methods
S.N. |
Method & Description |
1 |
*void addLayoutComponent(Component comp, Object constraints) * Adds the specified component to the layout, using the specified constraint object. |
2 |
*float getLayoutAlignmentX(Container target) * Returns the alignment along the x axis. |
3 |
*float getLayoutAlignmentY(Container target) * Returns the alignment along the y axis. |
4 |
void invalidateLayout(Container target) Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. |
5 |
*Dimension maximumLayoutSize(Container target) * Calculates the maximum size dimensions for the specified container, given the components it contains. |
AWT BorderLayout Class
Introduction
类 BorderLayout 安排组件以适合五个区域:东、西、北、南和中心。每个区域只能包含一个组件,并且每个区域中的每个组件都由相应的常量 NORTH、SOUTH、EAST、WEST 和 CENTER 标识。
The class BorderLayout arranges the components to fit in the five regions: east, west, north, south and center. Each region is can contain only one component and each component in each region is identified by the corresponding constant NORTH, SOUTH, EAST, WEST, and CENTER.
Class declaration
以下为 java.awt.BorderLayout 类的声明:
Following is the declaration for java.awt.BorderLayout class:
public class BorderLayout
extends Object
implements LayoutManager2, Serializable
Field
以下为 java.awt.BorderLayout 类的字段:
Following are the fields for java.awt.BorderLayout class:
-
*static String AFTER_LAST_LINE * — Synonym for PAGE_END.
-
*static String AFTER_LINE_ENDS * — Synonym for LINE_END.
-
*static String BEFORE_FIRST_LINE * — Synonym for PAGE_START.
-
*static String BEFORE_LINE_BEGINS * — Synonym for LINE_START.
-
*static String CENTER * — The center layout constraint (middle of container).
-
*static String EAST * — The east layout constraint (right side of container).
-
*static String LINE_END * — The component goes at the end of the line direction for the layout.
-
*static String LINE_START * — The component goes at the beginning of the line direction for the layout.
-
*static String NORTH * — The north layout constraint (top of container).
-
*static String PAGE_END * — The component comes after the last line of the layout’s content.
-
*static String PAGE_START * — The component comes before the first line of the layout’s content.
-
*static String SOUTH * — The south layout constraint (bottom of container).
-
*static String WEST * — The west layout constraint (left side of container).
Class constructors
S.N. |
Constructor & Description |
1 |
*BorderLayout() * Constructs a new border layout with no gaps between components. |
2 |
*BorderLayout(int hgap, int vgap) * Constructs a border layout with the specified gaps between components. |
Class methods
S.N. |
Method & Description |
1 |
*void addLayoutComponent(Component comp, Object constraints) * Adds the specified component to the layout, using the specified constraint object. |
2 |
*void addLayoutComponent(String name, Component comp) * If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name. |
3 |
*int getHgap() * Returns the horizontal gap between components. |
4 |
*float getLayoutAlignmentX(Container parent) * Returns the alignment along the x axis. |
5 |
*float getLayoutAlignmentY(Container parent) * Returns the alignment along the y axis. |
6 |
*int getVgap() * Returns the vertical gap between components. |
7 |
*void invalidateLayout(Container target) * Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. |
8 |
*void layoutContainer(Container target) * |
9 |
*Dimension maximumLayoutSize(Container target) * Returns the maximum dimensions for this layout given the components in the specified target container. |
10 |
*Dimension minimumLayoutSize(Container target) * Determines the minimum size of the target container using this layout manager. |
11 |
Dimension preferredLayoutSize(Container target) Determines the preferred size of the target container using this layout manager, based on the components in the container. |
12 |
*void removeLayoutComponent(Component comp) * Removes the specified component from this border layout. |
13 |
*void setHgap(int hgap) * Sets the horizontal gap between components. |
14 |
*void setVgap(int vgap) * Sets the vertical gap between components. |
15 |
*String toString() * Returns a string representation of the state of this border layout. |