Course index
[Before class thinking] 1. The Java language is a cross-platform programming language, so how does the graphical user interface be cross-platform? 2. What components and containers have AWT? What is their respective methods? 3. What is the event handling model of AWT? What is the principle? 5.1 Generate a graphical user interface with AWT
Abstract Window Toolkit AWT (Abstract Window Toolkit) is an API to create a graphics user interface toolset provided by Java programs, AWT available in Java's Applet and Applications. It supports graphical user interface programming features: user interface components; event processing models; graphics and image tools, including shapes, color, and font classes; layout managers, the flexible window layout and distinguish between the size and screen of the specific window The rate is independent; the data transfer class can be cut and pasted through the clipboard of the local platform.
5.1.1 java.awt package
The class and interfaces used in the Java.awt package can be seen from Figure 5.1 to see the relationship between major classes.
The Java.awt package provides the GUI design tool for the basic Java program. Mainly include the three concepts described above: Components - Component Containers - Container Layout Manager --LayoutManager
5.1.2 Components and containers
The most basic component of the Java graphical user interface is component, component is an object that can be displayed on the screen in a graphical manner, such as a button, a tag, and the like. Components cannot be independently displayed, and the components must be placed in a certain container to be displayed.
Class java.awt.component is the parent class of many component classes. Components and properties are encapsulated in the Component class, such as component objects, size, display location, foreground color, borders, visibility, etc. Many component classes also inherit the members of the Component class and member variables. The corresponding member methods include: getComponentat (int x, int y) getFont () getForeground () getName () getSize () Paint (graphics g) repaint () Update () setvisible (boolean b) Setsize (String Name) container is also a class, which is actually a subclass of Component, so the container itself is also a component, with all the nature of the component, but it The main function is to accommodate other components and containers. LayoutManager: Each container has a layout manager, which calls its corresponding layout manager when the container needs to position or determine its size size.
In order to make our generated graphical user interface with a good platform independent, in the Java language, the layout manager is provided to manage the layout of the component in the container without using the way the component location and size.
To schedule the location and size of the components in the program, you should pay attention to the following two points: 1. The layout manager in the container is responsible for the size and position of each component, so the user cannot set these properties of the component in this case. If you try to use the setlocation () (), setsize (), setbounds (), etc. provided using the Java language, will be overwritten by the Layout Manager.
2. If the user does need to set the component size or position in person, the layout manager of the container should be canceled, and the method is: setLayout (null); 5.1.3 Common container
Container Java.awt.Container is a subclass of Component, and a container can accommodate multiple components and make them a whole. The container can simplify the design of the graphical interface to arrange the interface in an overall structure. All containers can add components to the container via the add () method. There are three types of containers: Window, Panel, Scrollpane, commonly used panel, frame, applet.
1. Frame
example:
Import java.awt. *; public class myframe extends frame {public static void main (string args []) {myframe fr = new myframe ("Hello Out there!"); // Configuration method fr.setsize (200, 200); / / Set the size of the frame, default is (0) fr.setBackground (color.red); // Setting the background of the frame, the default is red fr.setVisible (TRUE); // Setting Frame is visible, default For invisible} public myframe (string str) {super (STR); // call the parent class constructor}}
Generally we want to generate a window, usually use Window subclass frame to instantiate, not directly to the Window class. The appearance of the frame is like the windows we are usually seen under the Windows system, with title, border, menu, size, and so on. After instantiation of each frame, it is not sized and invisible, so setsize () must be called to set the size, call SetVisible (TRUE) to set the window to see. In addition, AWT is a graphics system that calls the platform in the actual operation, so the same AWT program is different in different operating system platforms. For example, running under Windows, the displayed window is a Windows style window; while running in UNIX, the Unix style window is displayed.
2. Panel
Panel is similar to Frame, which can be added to the FRAME.
5.1.4 LayoutManager Layout Manager (1)
In order to achieve cross-platform features and achieve dynamic layout effects, Java arranges all components in the container to a "layout manager" to manage, such as: arrangement order, component, location, after the window moves or resizes How to change the function to manage the corresponding container layout manager, different layout managers use different algorithms and policies, and the container can determine the layout by selecting different layout managers.
The layout manager mainly includes: FlowLayout, BorderLayout, GridLayout, Cardlayout, GridbagLayout:
1. FlowLayout FlowLayout is the default layout manager of Panel, Applet. The lap of its components is placed from left to right. If the container is wide enough, the first component is added to the left side of the first row in the container, and the subsequent components are added to the right side of the previous component. If the current row is already placed, it is placed to the leftmost left side of the next row. When the size of the container changes, the components managed with FlowLayout will change, and the variation is: the size of the component is unchanged, but the relative position changes. For example, there are three buttons in the figure above, but if the window is narrowed, narrow to the next button, the second button will be folded to the second line, the third button will be folded to the third line. . The button "Open" was originally on the right side of the button "OK", but now, it is now below, so "said the size of the component constant, but the relative position will change." The structure is mainly below: FlowLayout (FlowLayout.right, 20, 40); / * The first parameter represents the alignment of the component, and the location in this line is aligned in this line, and the right is aligned or the left is left. Two parameters are lateral intervals between components, and the third parameter is the longitudinal interval between components, and the unit is pixel. * / FlowLayout (FlowLayout.Left); // 居 齐 齐 对 象 象 象 象 象 象 象 象 象 象 象 象 象 象 象 象 象 象 象 象 象 象 象; 象;; Value 5 pixels
example:
Frame f = new frame (); f.setLayout (New flowLayout ()); f.Add (New Button)); F.Add (New Button)); f.add (New Button) ("Close")); 2. BorderLayout BorderLayout is the default layout manager for Window, Frame, and Dialog. BorderLayout Layout Manager divides the container into 5 areas: North, South, East, West and Center, each area can only place a component. The position and size of each region are shown below:
F.setLayout (New BorderLayout ()); F.Add ("North", New Button ("north")); // The first parameter indicates the North region of the button to the container.
When using BorderLayout, if the size of the container changes, its variation is: the relative position of the component is constant, and the size changes. For example, the container becomes higher, then the North, the South region is constant, WEST, CENTER, EAST region becomes high; if the container is widened, WEST, EAST area is unchanged, North, Center, and South area are widened. Not necessarily all of the regions, if there is no component around the area (West, East, North, South District), it is added by the Center area, but if there is no component in the Center area:
NORTH and CENTER regions lack components
3. GridLayout makes the various components in the container, with an average space of the container.
Frame f = new frame ("gridLayout"); F.setLayout (New GridLayout (3, 2)); // Container averages 3 rows 2 columns a total of 6 grid F.Add (New Button); / / Add to the first line of F.Add (New Button)); // Add to the next grid F.Add (New Button)); // Add To the first line of the second line 4. CardLayout Cardlayout Layout Manager can help users handle two to more members share the same display space, which divides the container into many layers, and the display space of each layer occupies the size of the entire container, but Each layer only allows a component to be placed, of course, each layer can utilize Panels to implement complex user interfaces. The card layout manager (Cardlayout) is like a stronger playing card, there are 54 cards, but you can only see the top one, each card is equivalent to the list of layout manager. Every layer.
5. The nest of the container is designed in a complex graphical user interface. In order to make the layout more easily managed, a simple overall style, a container containing a plurality of components itself can also be added to another container as a component, in the container Add the container, so that the nesting of the container is formed. Below is an example of a container nested.
Example: f = new frame ("GUI EXAMPLE 3"); BW = New Button ("West"); BC = New Button ("Work Space Region"); F.Add (BW, "West"); f.Add (BC, "Center"); p = new panel (); f.Add (p, "north"); bfile = new button; bhelp = new button ("help"); P.ADD ( BFILE); P.Add (bhelp); f.Pack (); f.setvisible (true);
Small knot: 1. Frame is a top window. Frame's default layout manager is BorderLayout. 2. Panel cannot be displayed separately and must be added to a container. Panel's default layout manager is flowlayout. 3. When the Panel is added to a container as a component, the Panel still has its own layout manager. Therefore, it is possible to use Panel to make a plurality of components in a region in BorderLayout to achieve the purpose of designing complex user interfaces. 4. If you use a non-layout manager setLayout (NULL), you must use setLocation (), setsize (), setbounds () and other methods to manually set the size and location of the component, which causes the platform to be related and not encouraged.
5.2 AWT Event Processing Model To allow the graphical interface to receive the user's operation, you must add an event processing mechanism to each component. In the process of event processing, three types of objects are mainly involved:
◇ Event-Event, the user's description of the interface operation in the Java language, appears in the form of a class, such as the event class corresponding to the keyboard operation is KEYEVENT. ◇ Event source-Event source, events occurring, usually each component, such as button button. ◇ Event Handler-Event handler, receive event objects and processed objects. Since multiple events may occur due to the same event source, Java has taken the execution model, and the event source can handle the events that have the possible events thereof separately to different event handlers. For example, in the Canvas object, there may be a mouse event or a keyboard event. The Canvas object can authorize the event handler to process the mouse event while authorizing the event handler two to handle the keyboard event. Sometimes the event handler is also called a listener. The main reason is that the listener time monitors all event types on the event source, once the event type is consistent with the type of event handles it, it will be handled immediately. The authorization model will delegate the process of the event to the external processing entity to achieve a mechanism that separates the event source and the listener. Event handler (listener) is usually a class, and if you want to process some type of event, you must implement an interface with the event type. For example, Example 5.9 The class BUTTONHANDLER can handle an ActionEvent event because it implements interface ActionListener corresponding to the ActionEvent event. Each event class has an interface corresponding to it. Separate event source objects and event processors (event listeners). As shown in Figure 5.2
Example 5.9 Import Java.awt. *; Import Java.awt.Event. *; Public Class TestButton {PUBLIC Static Void Main (String Args []) {Frame F = New Frame ("Test"); Button B = New Button "Press Me!"); B.AddActionListener (New ButtonHandler ()); / * Registering the listener for authorization, the parameter of this method is an event handler object, and the type of event to be processed can be seen from the method name, such as this Methods To authorize the ActionEvent because the method name is AddActionListener. * / F.setLayout (new flowLayout ()); // Setting the layout manager F.Add (b); F.setsize (200, 100); f.setVisible (true);}} Class ButtonHandler Implements ActionListener {// Implement Interface ActionListener can do an event ActionEvent's processor public void actionPerformed (ActionEvent E) system generated ActionEvent event object is passed as a parameter to this method {System.out.Println ("Action Occurred"); // This interface has only one Method, so the event occurs, the system automatically calls this method, and the operation you need to write is written in a method. }
The general method of event processing using the authorization processing model is summarized as follows: 1. For some type of event XXXEvent, you must define the corresponding event listener class, which needs to implement the interface XXXListener; 2. After the event source is instantiated, authorization must be licensed, registering the listener of the class event, using the AddXxxListener method to register the listener. 5.2.1 All event classes related to the event class are derived from the java.awt.awtevent class, which is also subclasses of the EventObject class. The AWT event has a total of 10 categories, which can be classified as two categories: low-level events and advanced events.
The Java.util.EventObject class is the basic parent class of all event objects, and all events are derived from it. AWT's related events inherit in the Java.awt.awtevent class, these AWT events are divided into two categories: low-level events and advanced events, low-level events refer to components based on components and containers, when events occurred on one component, such as: mouse Enter, click, drag and drop, etc., or the window switch of the component, the component event is triggered. Advanced events are semantic-based events, which can be associated with a specific action, depending on the class that triggers this event, such as pressing the ENTER button in TextField to trigger an ActionEvent event, the sliding scroll bar will trigger an AdjustmentEvent event, or select A item of the project list triggers the ItemEvent event. ◇ Low-level events ComponENTEVENT (Component Event: Moving) ContaineRevent (Container Event: Components Increase, Mobile) WindowEvent (Window Event: Close Window, Window Close, Icons) Focusevent (Focus Event: Focus Get and Loss) KeyEvent (Keyboard Event: Key Press, Release) Mouseevent (Mouse Event: Mouse Click, Move)
◇ Advanced Events (Semantic Event) ActionEvent (Action Event: Button Press, Press ENTFIELD) AdjustmentEvent (Adjusting Event: Moving the Slider on the Scroll Bar to adjust the value) ItemEvent (Project Event: Select Project, Do not choose "project Change ") TextEvent (text event, text object change)
5.2.2 Event Listener Events each type of event has a corresponding event listener, the listener is an interface, defining the method according to the action.
Method for registering and logging out the listener in the component class: ◇ Registration listener: public void add
For example, the Button class :( check API) public class Button extends Component {...... public synchronized void addActionListener (ActionListener l); public synchronized void removeActionListener (ActionListener l); ......} 5.2.3 AWT event listener interface and its corresponding ( 1) Table 5.1 lists all AWT events and its corresponding listener interface, a total of 10 events, 11 interfaces. The table below should be able to remember.
Table 5.1
Event category
Description
Interface name
method
ActionEvent
Activate component
ActionListener
ActionPerformed (ActionEvent)
ItemEvent
Choosing some items
Itemlistener
ItemStateChanged (itemEvent)
Mouseevent
Mouse movement
MouseMotionListener
mouseDragged (MouseEvent) Mousemoved (MouseEvent)
Mouse click, etc.
Mouselistener
MousePressed (MouseEvent) mouseelected (mouseevent) mouseexited (mouseevent) mouseclicked (mouseevent)
KeyEvent
keyboard input
Keylistener
Keypressed (KeyEvent) Keyreleased (KeyEvent) Keytyped (KeyEvent)
Focusevent
Components receive or lose focus
FocusListener
FocusGained (Focusevent) Focuslost (Focusevent)
Adjustmentevent
Move the scroll bar and other components
AdjustmentListener
AdjustmentValueChanged (AdjustMENTEVENT)
Componentevent
Object mobile zoom display hidden, etc.
ComponentListener
ComponentMoved (ComponENTEVENT) Componenthidden (ComponENTEVENT) ComponentShown (ComponENTEVENT)
WindowEvent
Window receives a window level event
Windowlistener
windowClosing (WindowEvent) windowOpened (WindowEvent) windowIconified (WindowEvent) windowDeiconified (WindowEvent) windowClosed (WindowEvent) windowActivated (WindowEvent) windowDeactivated (WindowEvent)
Containerevent
Add to delete components in the container
Containerlistener
Componentadded (Containerevent) Componentremoved (Containerevent)
TextEvent
Text field or change in text
TextListener
TextValueChanged (TextEvent)
5.2.3 AWT event and its corresponding listener interface (2)
1. You can declare multiple interfaces, and the interfaces are separated from commas. ...... Implements MouseMotionListener, Mouselistener, Windowlistener;
2. Multiple events that occur on an event source can be listened by the same object: f.addmouseMotionListener (this); f.addmouselistener (this); f.addwindowlistener (this); multiple events occurred on object F will be A listener receives and processes. 3. Event handlers and event sources are in the same class. In this example, the event source is Frame F. The event handler is class ThreeElistener, where the event source Frame F is a member variable of THREELISTENER. All event listener methods are declared in the primary class here. Public Class ThreeElistener Implements MouseMotionListener, MouseListener, Windowlistener {
f = new frame ("Three Listener Example");
F.AddmouseMotionListener (this); // Register the listener MouseMoteListener F.Addmouselistener (this); // Register the listener mouselistener f.addwindowlistener (this); // Register listener WindowListener
} 4. Details can be obtained by event objects, such as in this example, the coordinate value when the mouse occurs through the event object. Public void mousedragged (mouseevent e) {string s = "mouse Dragging: x =" E.GETX () "y =" E.Gety (); tf.settext (s);} Java language class is very Dictionary, thus only support single inheritance, in order to achieve multiple inheritance, Java is implemented, a class can implement multiple interfaces, which is more simple, flexible and stronger than multiple inheritance. Declaration and implementation of multiple interfaces are often used in AWT. Remember whether there are several interfaces, the method defined in the interface must be implemented one by one, and if it is not interested in an event, it can be replaced with an empty method. But you must write all methods.
5.2.4 Event Adapter Java Language provides an Adapter class for some Listener interfaces. You can rewrite the need for the Adapter class corresponding to the inheritance, no need to implement it. The event adapter provides us with a simple means of realizing the listener, which can shorten the program code. However, due to the single inheritance mechanism of Java, the event adapter cannot be employed when multiple listeners or such a parent class is needed.
1. The Mouse Adapter: Import Java.awt. *; Import Java.awt.Event. *; PUBLIC Class MouseClickHandler Extends MouseadaPer {Public Void Mouseclicked (MouseEvent E) // Realization Method { ...}}
The event adapter classes defined in the java.awt.event package include the following: 1. ComponentAdapter 2. ContaineraDapter 3. FocusAdapter 4. KeyAdapter 5. MouseAdapter 6. MouseMotionAdapter 7. WindowAdapter (window adapter)
2. Inner Class Event Processing Inner Class (Inner Class) is a class defined in another class, the main reason for using the internal class is due to: ◇ An internal class object can access the members of the external class and variables, Includes private members. ◇ When implementing an event listener, an internal class is used, and anonymous class programming is very easy to implement its function. ◇ Write an event driver, which is very convenient. Note: The internal class used cannot be called in a static method (such as the main method). Example 5.11 Import Java.awt. *; Import Java.awt.Event. *; Public Class InnerClass {Private Frame F; Private TEXTFIELD TF; Public InnerClass () {f = new frame ("inner classes example"); tf = new TextField (30);} public voidi launchframe () {label label = new label ("Click and Drag The Mouse"); F.Add (Label, BorderLayout.North); F.Add (TF, BorderLayout.South); f .addmouseMotionListener ()); / * Parameter is internal class object * / f.setsize (300, 200); f.setVisible (true);}
Class MyMouseMotionListener Extends MouseMotionAdapter {/ * Internal Class Start * / Public Void MouseDragged (MouseEvent E) {String S = "Mouse Dragging: x =" E.GETX () "y =" E.Gety (); TF. Settext (s);}};
Public static void main (string args []) {innerclass obj = new innerclass (); obj.launchframe ();}} // internal class end}
3. Anonymous Class When an internal class's class sound name is just once when you create such objects, and the new categories you want to inherit in an existing parent class or implement an interface, you can think about anonymous classes. Since the anonymous class is not named, it does not have a constructor, which needs to display a construction method of a non-arranging parent class, and rewrite the method of the parent class. The so-called anonymity is that the type of even name is not, but only the constructor of the parent class is called.
Example 5.12 F.AddmouseMotionListener (New MouseMotionAdapter () {// Anonymous class start public void mousedragged (mouseEvent E) {string s = "mouse Dragging: x =" E.GETX () "y =" E.GETY ); Tf.settext (s);}}); // End of anonymous class
5.3 AWT component library
This section further introduces some components of the AWT from the perspective of the application, which makes you deepen the understanding of the AWT, master how to construct a graphical user interface with a variety of components, learn the color and font of the component. Here are some common components: 1. The Button button is the most common component, its constructor is: Button B = New Button ("quit"); After the button is clicked, an ActionEvent Event will be generated, and the ActionListener interface is required to monitor and process events. ActionEvent's object calls the getActionCommand () method to get the ID name of the button, the default button name is label. Use setActionCommand () to set the component identifier for the button.
2. Checkbox checkbox provides a simple "ON / OFF" switch, next to the text tab. The constructor is as follows: setLayout (New GridLayout (3,1)); Add ("One", NULL, TRUE); Add (New Checkbox)); Add (New Checkbox ("Three") ); Check box Use itemListener to get the ItemEvent event, get the current state with getStateChange () when the check box status changes. Use GetItem () to get the string object of the modified check box.
class Handler implements ItemListener {public void itemStateChanged (ItemEvent ev) {String state = "deselected"; if (ev.getStateChange () = = ItemEvent.SELECTED) {state = "selected"} System.out.println (ev.getItem ( ) " state);}}
3. CheckboxGroup Use the checkbox group to implement the functionality of the radio box. The method is as follows: setLayout (New GridLayout (3, 1)); CheckboxGroup CBG = New CheckboxGroup (); add (New Checkbox ("One", CBG, True); Add (New Checkbox ("Two", CBG, FALSE) Add ("Three", CBG, False); 4. The drop-down menu (Choice) drop-down menu can only select one of them each time, it can save display space for a lot of options. Choice colorchooser = new choice (); colorchooser.add ("green"); colorchooser.add ("red"); colorchooser.add ("blue"); Choice uses the itemListener interface to monitor 5. Canvas an application must inherit The Canvas class can get useful features, such as creating a custom component. If you want to complete some graphic processing on the canvas, the PAINT () method in the Canvas class must be rewritten. The Canvas component monitors a variety of mice, keyboard events. When you enter characters in the Canvas component, you must first call the RequestFocus () method. 6. A single-line text input area can only display a line. When the Enter key is pressed, an ActionEvent event occurs, and an event can be processed by an actionPerformed () method in ActionListener. You can use the setDitable (Boolean) method to read-only properties. Single line text input area constructor is as follows: TextField TF1, TF2, TF3, TF4: TF1 = New TextField (); TF2 = New TextField (", 20); // The display area is 20 columns TF3 = New TextField (" Hello! "); // Press the text area size to display TF4 = New TextField (" Hello! ", 30); // The initial text is Hello !, 30 columns in the display area
7. TextArea TextArea can display multi-row of multi-column text. Using the setEditable (Boolean) method, you can set it to read only. A horizontal or vertical scroll bar can be displayed in TextArea. To determine if the text is entered, you can set a button next to TextArea, and the input text is processed by clicking the generated ACTIONEvent.
8. List (list) list provides multiple text options, the list supports scroll bar, you can browse multiple list lst = new list (4, false); // The two parameters represent the number of lines displayed, whether to allow multiple LST.Add ("VENUS"); LST.Add ("Earth"); LST.Add ("JavaSoft"); LST.Add ("Mars"); cnt.add (LST);
9. Frame Frame is a top window that displays a title, reset size. When Frame is turned off, a WindowEvent event will be generated, and Frame cannot directly listen to the keyboard input event.
10. Dialog (Dialog) It is a subclass of a Window class. The difference between dialogs and general windows is that it relies on other windows. The dialog is divided into two types of non-modal and modal. 11. File dialog (FileDialog) When the user wants to open or store files, use the File dialog box. The main code is as follows: FileDialog D = New FileDialog (PARENTFR, "FileDialog"); D.SetVisible (TRUE); string filename = d.GetFile ();
12. Menu (MENU) Unable to add a menu to a certain location of the container, and cannot be controlled using the layout manager. The menu can only be added? Quot; menu container "(menubar).
13. MenuBar can only be added to the Frame object, as the foundation of the entire menu tree. Frame fr = new frame ("menubar"); menubar MB = new menubar (); fr.setmenubar (MB); fr.setsize (150, 100); fr.setvisible (TRUE);
14. Menu drop-down menu. It can be added to menubar or in other Menu. Frame fr = new frame ("menubar"); MenuBar MB = new menubar (); fr.setmenubar (MB); MNU m1 = new menu ("file"); Mb.Add (m1); 15. MenuItem MenuItem is a menu "Leaf Node" in the tree. Menuitem is usually added to a MENU. ActionListener can be added to the MenuItem object so that it can complete the corresponding operation. Menu m1 = new menu ("file"); menuitem mi1 = new menuItem ("save");
16. Component and listener lists the correspondence between individual components and all listeners,
"Indicates that the component can be registered with such listeners. Table 5.2
Search interface
ACT
Adj
CMP
CNT
FOC
ITM
Key
Mou
Mm
TEXT
Win
Button
Canvas
Checkbox
CheckBoxMenuItem
Choice
Component
Container
Dialog
Frame
Label
List
Menuitem
Panel
Scrollbar
Scrollpane
Textarea
Textfield
Window
Act = ActionListener Adj = AdjustmentListener Cmp = ComponentListener Cnt = ConatainerListener Foc = FocusListener Itm = ItemListener Key = KeyListener Mou = MouseListener MM = MouseMotionListener Text = TextListener Win = WindowListener
[本 讲 小]