Note: Lesson 5 AWT graphical user interface design
[thinking before class] 1. Java language is a cross platform programming language, so how can the graphical user interface be cross platform? 2. What are the components and containers of AWT? What are their respective use methods? 3. What is the event processing model of AWT? What is the principle?
5.1 generate graphical user interface with AWT
Abstract window toolkit (AWT) is a tool set for establishing graphical user interface GUI (graphics user interface) provided by API for Java programs. AWT can be used in Java applets and applications. It supports the functions of graphical user interface programming, including: user interface components; Event handling model; Graphics and image tools, including shape, color and font; The layout manager can carry out flexible window layout regardless of the size and screen resolution of a specific window; Data transfer class, which can be cut and pasted through the clipboard of the local platform.
5.1. 1 java. AWT package
java. AWT package provides the classes and interfaces used in GUI design. You can see the relationship between the main classes in Figure 5.1.
java. AWT package provides basic GUI design tools for Java programs. It mainly includes the following three concepts: component -- component container -- container layout manager -- layoutmanager
5.1. 2 components and containers
The most basic component of java graphical user interface is component. A component is an object that can be displayed on the screen graphically and interact with users, such as a button, a label, etc. components cannot be displayed independently, and they must be placed in a certain container.
Class java awt. Component is the parent class of many component classes, which encapsulates the common methods and properties of components, such as component object, size, display position, foreground and background color, boundary, visibility, etc. Therefore, many component classes inherit the member methods and member variables of component class, Corresponding member methods include: getcomponentat (int x, int y) getfont () getforegroup () getname () getSize () paint (graphics g) retain () update () setvisible (Boolean b) SetSize (dimension D) setname (string name) and other containers It is also a class, which is actually a subclass of component. Therefore, the container itself is also a component and has all the properties of components, but its main function is to accommodate other components and containers. Layout manager: each container has a layout manager. When a container needs to locate a component or determine its size, it will call its corresponding layout manager.
2. If the user really needs to set the component size or location himself, the layout manager of the container should be cancelled. The method is: setlayout (null);
Generally, we need to generate a window. We usually instantiate it with the sub class frame of window, rather than directly using the window class. The appearance of frame is like the window we usually see under Windows system, including title, border, menu, size and so on. After the instantiation of each frame object, it has no size and is invisible. Therefore, you must call setsize() to set the size and setvisible (true) to set the window to be visible. In addition, AWT calls the graphics system of the platform in the actual operation process, so the graphics system seen by the same AWT program running under different operating system platforms is different. For example, when running under windows, the displayed window is windows style window; When running under UNIX, a UNIX style window is displayed.
2.Panel
Panel is similar to frame and can be added to frame.
5.1. 4 layoutmanager layout manager (1)
In order to realize the cross platform feature and obtain dynamic layout effect, Java arranges all components in the container to a "layout manager" for management, such as arrangement order, size and position of components, how components change after the window is moved or resized, and other functions are authorized to the corresponding container layout manager for management, Different layout managers use different algorithms and strategies. Containers can determine the layout by selecting different layout managers.
The layout manager mainly includes flowlayout, borderlayout, GridLayout, CardLayout and gridbaglayout:
1. Flowlayout flowlayout is the default layout manager of panel and applet. The placement rule of its components is from top to bottom and from left to right. If the container is wide enough, the first component will be added to the leftmost of the first row in the container, and the subsequent components will be added to the right of the previous component in turn. If the component cannot be placed in the current row, it will be placed to the leftmost of the next row.
When the size of the container changes, the components managed with flowlayout will change. The change law is that the size of the components remains the same, but the relative position will change. For example, there are three buttons in the same row in the above figure, but if you narrow the window so that one button can be put down, the second button will fold to the second row and the third button will fold to the third row. The button "open" was originally on the right side of the button "OK", but now it runs below, so it is said that "the size of the component remains unchanged, but the relative position will change". The construction methods are mainly as follows: flowlayout (flowlayout. Right, 20,40); / * the first parameter indicates the alignment mode of components, which refers to whether the components are aligned in the center, right or left in this row. The second parameter is the horizontal spacing between components, and the third parameter is the vertical spacing between components, in pixels*/ FlowLayout(FlowLayout.LEFT); / / align to the left. The horizontal interval and vertical interval are the default values of 5 pixels flowlayout(); / / the default alignment is center alignment. The horizontal spacing and vertical spacing are the default value of 5 pixels
Example:
Frame f = new Frame(); f.setLayout(new FlowLayout()); f.add(new Button("Ok")); f.add(new Button("Open")); f.add(new Button("Close")); 2. Borderlayout borderlayout is the default layout manager for window, frame and dialog. The borderlayout layout manager divides the container into five areas: North, South, East, West and center. Only one component can be placed in each area. The location and size of each area are shown in the figure below:
f.setLayout(new BorderLayout()); f.add("North",new Button("North")); / / the first parameter indicates that the button is added to the north area of the container
When using borderlayout, if the container size changes, the change law is: the relative position of components remains unchanged, and the size changes. For example, if the container becomes higher, the north and south areas remain unchanged, and the west, center and east areas become higher; If the container becomes wider, the West and east areas remain unchanged, and the north, center and south areas become wider. Not all areas may have components. If there are no components in the surrounding areas (West, East, North and South), the center area will supplement them. However, if there are no components in the center area, it will remain blank:
The north and center areas are missing components
3. GridLayout enables the components in the container to be arranged in a grid shape, occupying the space of the container on average.
Frame f = new Frame("GridLayout"); f.setLayout(new GridLayout(3,2)); // The container is divided into 3 rows and 2 columns on average, with a total of 6 cells f.add (New button ("1"))// F. add (New button ("2")) added to the first cell of the first row// Add to the next cell f.add (New button ("3")) in the first row// Add to the first cell of the second row
4. CardLayout CardLayout layout manager can help users deal with two or more members sharing the same display space. It divides the container into many layers. The display space of each layer occupies the size of the whole container, but only one component is allowed in each layer. Of course, each layer can use panel to realize complex user interface. The card layout manager is like a stack of playing cards. There are 54 cards, but you can only see the top card. Each card is equivalent to each layer in the card layout manager.
5. The nesting of containers is in the complex graphical user interface design. In order to make the layout easier to manage and have a concise overall style, a container containing multiple components can also be added to another container as a component, and then add containers to the container, thus forming the nesting of containers. The following is an example of container nesting.
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("File"); bhelp= new Button("Help"); p.add(bfile); p.add(bhelp); f.pack(); f.setVisible(true);
Summary: 1. Frame is a top-level window. The default layout manager for frame is borderlayout. 2. The panel cannot be displayed separately and must be added to a container. The default layout manager of the panel is flowlayout. 3. When a panel is added to a container as a component, the panel can still have its own layout manager. Therefore, the panel can be used to display multiple components in a certain area of the borderlayout to achieve the purpose of designing a complex user interface. 4. If setlayout (null) without layout manager is adopted, the size and location of components must be set manually by using setlocation(), setsize(), setboundaries(). This method will lead to platform dependence and is not encouraged.
5.2 AWT event handling model
To enable the graphical interface to receive user operations, you must add 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 Java language, appears in the form of a class. For example, the event class corresponding to the keyboard operation is keyevent. ◇ event source - event source, the place where the event occurs, usually each component, such as a button. ◇ event handler - event handler, the object that receives and processes the event object.
Because multiple events may occur on the same event source, Java adopts a delegation model. The event source can authorize all possible events to different event handlers. For example, both mouse events and keyboard events may occur on the canvas object. The canvas object can authorize the event handler to handle mouse events and the event handler to handle keyboard events. Sometimes the event handler is also called a listener. The main reason is that the listener always listens to all event types on the event source. Once the event type is consistent with the event type it is responsible for processing, it will be processed immediately. The authorization model delegates the processing of events to external processing entities for processing, and realizes the mechanism of separating event source and listener. Event handler (listener) is usually a class. If this class wants to be able to handle certain types of events, it must implement the interface corresponding to this event type. For example, the reason why the class buttonhandler in example 5.9 can handle ActionEvent events is that it implements the interface actionlistener corresponding to ActionEvent events. Each event class has a corresponding interface Separate the event source object from the event handler (event listener), 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()); /* Register the listener for authorization. The parameter of this method is the event handler object. The event type to be processed can be seen from the method name. For example, this method is authorized to process ActionEvent because the method name is addactionlistener*/ f.setLayout(new FlowLayout()); // Set the layout manager f.add (b); f.setSize(200,100); f.setVisible(true); }} class buttonhandler implements actionlistener {/ / only by implementing the interface actionlistener can you be the handler of the event ActionEvent public void actionperformed (ActionEvent E) / / the ActionEvent object generated by the system is passed to the method {system.out.println as a parameter ("Action occurred"); / / there is only one method in this interface. Therefore, when an event occurs, the system will automatically call this method, and write the code in the method. The general methods of event processing using authorization processing model are summarized as follows: 1. For a certain type of event xxxevent, to receive and process this kind of event, you must define the corresponding event listener class, which needs to implement the interface xxxlistener corresponding to the event; 2. After the event source is instantiated, it must be authorized to register the listener of this kind of event, and use the addxxxlistener (xxxlistener) method to register the listener.
5.2. 2 event listener each type of event has a corresponding event listener, which is an interface and defines methods according to actions.
5.2. 3 AWT events and their corresponding listener interfaces (1) table 5.1 lists all AWT events and their corresponding listener interfaces, a total of 10 types of events and 11 interfaces. The following table should be remembered. Table 5.1
5.2. 3 AWT event and its corresponding listener interface (2)
1. Multiple interfaces can be declared, separated by commas. ……implements MouseMotionListener,MouseListener,WindowListener;
2. Multiple events on an event source can be monitored by the same object: f. addMouseMotionListener (this); f.addMouseListener(this); f.addWindowListener(this); Then multiple events occurring on object f will be received and processed by the same listener. 3. The event handler and the event source are in the same class. In this example, the event source is frame f, and the event handler is class threelistener, where the event source frame f is a member variable of class threelistener. Here, all event listener methods are declared in the main class.
public class ThreeListener implements MouseMotionListener,WindowListener {
f = new Frame("Three listeners example");
f.addMouseMotionListener(this); // Register the listener mousemotionlistener f.addmouselistener (this)// Register the listener mouselistener f.addwindowlistener (this)// Register listener windowlistener
}4. You can obtain detailed information through the event object. For example, in this example, you can obtain 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 classes are very hierarchical, so they only support single inheritance. In order to realize the ability of multiple inheritance, Java uses interfaces. A class can implement multiple interfaces, This mechanism is simpler, more flexible and more powerful than multiple inheritance. In AWT, it is often used to declare and implement multiple interfaces. Remember that no matter how many interfaces are implemented, the methods defined in the interface must be implemented one by one. If you are not interested in an event, you can use an empty method body instead of implementing its methods. But all methods must be written down.
5.2. 4 event adapter Java language provides adapter classes for some listener interfaces. You can override the required methods by inheriting the adapter class corresponding to the event, and the irrelevant methods do not need to be implemented. The event adapter provides us with a simple means to implement the listener, which can shorten the program code. However, due to the single inheritance mechanism of Java, the event adapter cannot be used when multiple listeners are required or this class has a parent class.
2. Use internal classes to implement event handling internal classes (inner class) is a class defined in another class. The main reason for using an inner class is that: ◇ the object of an inner class can access the member methods and variables of an outer class, including private members. ◇ when implementing an event listener, it is very easy to implement its functions by programming with inner classes and anonymous classes. ◇ write an event driver and use the inner class Class is very convenient.
3. Anonymous class (anonymous class) when the class name of an internal class is used only once when creating such an object, and the new class to be generated needs to inherit from an existing parent class or implement an interface, the anonymous class can be considered. Because the anonymous class itself is nameless, there is no construction method. It needs to explicitly call the construction method of a parameterless parent class, and Override the method of the parent class. The so-called anonymity is that the class does not even have a name, but explicitly calls the constructor of a parameterless parent class.
Example 5.12 f.addmousemotionlistener (New mousemotionadapter() {/ / anonymous class starts 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 AWT from the perspective of application, so as to deepen your understanding of AWT, master how to use various components to construct graphical user interface, and learn to control the color and font of components. Here are some common components:
1. Button button is the most commonly used component. Its construction method is: button B = new button ("quit"); When the button is clicked, an ActionEvent event will be generated. The actionlistener interface is required to listen and process the event. The object of ActionEvent can call getActionCommand () method to get the identification name of the button. The default button name is label. Use setactioncommand () to set the component identifier for the button.
2. Check box( Check@R_704_2419 @) the check box provides a simple "on / off" switch with a text label next to it. The construction method is as follows: setlayout (New GridLayout (3,1)); add(new Check@R_704_2419 @("one",null,true)); add(new Check@R_704_2419 @("two")); add(new Check@R_704_2419 @("three")); Check boxes use itemlistener to listen for itemevent events. When the check box state changes, use getstatechange() to get the current state. 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. Check box group( Check@R_704_2419 @Group) use the check box group to realize the function of radio box. The method is as follows: setlayout (New GridLayout (3,1)); Check@R_704_2419 @Group cbg = new Check@R_704_2419 @Group(); add(new Check@R_704_2419 @("one",cbg,true)); add(new Check@R_704_2419 @("two",false)); add(new Check@R_704_2419 @("three",false)); 4. Drop down menu (choice) the drop-down menu can only select one item at a time, which can save display space and is suitable for a large number of options. Choice colorchooser = new choice(); Colorchooser. add("Green"); Colorchooser. add("Red"); Colorchooser. add("Blue"); Choice uses the itemlistener interface to listen 5 Canvas an application must inherit the canvas class to obtain useful functions, such as creating a custom component. If you want to complete some graphics processing on the canvas, the paint() method in the canvas class must be overridden. The canvas component listens to various mouse and keyboard events. When entering characters in the canvas component, you must first call the requestfocus() method.
6. Only one line can be displayed in the single line textfield. When the Enter key is pressed, an ActionEvent event will occur. You can handle the event accordingly through the actionperformed() method in the actionlistener. You can use the seteditable (Boolean) method to set it as a read-only property. The construction method of single line text input area 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!")// Display by text area size tf4 = new textfield ("Hello!", 30); // The initial text is Hello!, The display area is 30 columns
7. Text input area textarea can display multiple lines and columns of text. It can be set as read-only by using seteditable (Boolean) method. Horizontal or vertical scroll bars can be displayed in textarea. To judge whether the text has been input, you can set a button next to the textarea to process the input text through the ActionEvent generated by clicking the button.
8. List: multiple text options are provided in the list. The list supports scroll bars and can browse multiple list LST = new list (4, false)// The two parameters respectively indicate the number of rows displayed and whether multiple selections are allowed lst add("Venus"); lst. add("Earth"); lst. add("JavaSoft"); lst. add("Mars"); cnt. add(lst);
9. Frame is a top-level window, which can display the title and reset the size. When the frame is closed, a windowevent event will be generated, and the frame cannot directly listen to keyboard input events. 10. Dialog is a subclass of window class. The difference between dialog and general window is that it depends on other windows. Dialog is divided into non mode (non modal) and mode (modal). 11. File dialog: when the user wants to open or store a file, use the file dialog to operate. The main codes are as follows: FileDialog d = new FileDialog (parentfr, "FileDialog"); d.setVisible(true); String filename=d.getFile(); 12. The menu cannot be directly added to a certain location of the container, nor can it be controlled by the layout manager. The menu can only be added to the "quote; menu container" (menubar). 13. The 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 the menubar or other menus. Frame fr = new Frame("MenuBar"); MenuBar mb = new MenuBar(); fr.setMenuBar(mb); Menu m1 = new Menu("File"); mb. add(m1); 15. MenuItem MenuItem is the "leaf node" in the menu tree. MenuItem is usually added to a menu. For the MenuItem object, you can add an actionlistener to enable it to complete the corresponding operation. Menu m1 = new Menu("File"); MenuItem mi1 = new MenuItem("Save"); 16. Correspondence between components and listeners the following table lists the correspondence between each component and all listeners. Marking "" indicates that the component can register such listeners. Table 5.2
Act=ActionListener Adj=AdjustmentListener Cmp=ComponentListener Cnt=ConatainerListener Foc=FocusListener Itm=ItemListener Key=KeyListener Mou=MouseListener MM=MouseMotionListener Text=TextListener Win=WindowListener