Java certification course 10

zhaozj2021-02-16  181

Chapter 10 AWT Component Library

JDK provides many components that create graphical user interfaces. This module examines these AWT components, as well as non-component AWT classes, such as prints of Color, Font, and graphical user interfaces.

Section 1 related issues

Discussion - The following problems are related to the content in this module:

You now know how to create a Java graphical user interface for graphical output and interactive user input. However, we only introduce some components that can create a graphical user interface. What is the use of other components in the graphical user interface?

Second section

After completing this module, you should be able to:

- Know the critical AWT component.

- For you a description of a user interface, you can create a user interface with AWT components.

- Give you an AWT program that can change the color and font of the AWT component.

- Use the Java printed mechanism to print a user interface.

The third quarter of AWT

AWT features

- AWT components provide control interface appearance, including colors and fonts

- AWT also supports printing (this is introduced in JDK1.1)

AWT provides a variety of standard features. This module will introduce the components you can use and outline some of the special situations you need to know.

First, each component of the AWT will be described. They are used to create user interfaces. You need to know all graphical user interface components so you can choose the right component when you create your own interface.

The AWT component provides a mechanism for controlling the appearance of the interface, including color and fonts for text display.

In addition, AWT also supports printing. This feature is introduced in JDK1.1.

10.3.1 Button

You have been familiar with the Button component. This component provides the basic user interface "press and action". A button with a text tag can be constructed to tell the user its role.

Button B = New Button ("Sample");

B. ADDACTIONLISTENER (THIS);

Add (b);

Any class that implements the ActionListener interface that is registered as a listener, and its actionPerformed () method will be called when a button is clicked in "Press" by the mouse.

Public Void ActionPerformed (ActionEvent AE) {

System.out.println ("Button Press Received.");

System.out.println ("Button's Action Command IS:" AE.GetActionCommand ());

}

The GetActionCommand () method called when the button is pressed will return the label string in the default. Use the setActionCommand () method of the button to change the action command and tag.

Button B = New Button ("Sample");

B.SetActionCommand ("Action Command Was Here!");

B. ADDACTIONLISTENER (THIS);

Add (b);

Note - The full source code of SampleButton and ActionCommandButton can be found in the course_examples directory.

10.3.2 checkbox (Checkbox)

The CheckBox component provides a simple "On / Off" input device, which has a text tag next to it.

Frame f = new frame ("checkbox")

Checkbox One = New Checkbox ("One", True;

Checkbox TWO = New Checkbox ("Two", False);

CheckBox Three = New Checkbox ("Three", True; One.Additemlistener (this)

Two.additemlistener (this);

Three.Additemlistener (this);

F.Add (one);

F.Add (TWO);

F.Add (three);

Events selected or not (canceled) a checkbox will be sent to the ItemListener interface. The transmitted item contains the getStateChange () method, which returns itemEvent.deselected or itemEvent.selected based on the actual situation. The GetItem () method will be affected as a String object that represents this check box tag.

Class Handler Implements Itemlistener {

Public void itemStateChanged (ItemEvent EV) {

String stat = "deselected";

IF (Ev.getStateChange () == itemEvent.selected) {

State = "SELECTED";

}

System.out.println (Ev.getItem () " State);

}

}

10.3.3 Check Box Group - Checkbox Group-Radio Button

The checkbox group provides a way to use multiple check boxes as a collection of mutually exclusive, so only one check box in this collection is true at any time. The check box for True is the currently selected check box. You can use a constructor with an additional checkboxgroup parameter to create each check box in a group. It is this CheckboxGroup object to connect each check box into a group. If you do this, then the appearance of the check box changes, and all check boxes associated with all check boxes will exhibit the behavior of the "radio box".

Frame f = new frame ("Checkbox Group");

CheckboxGroup CBG = New CheckboxGroup ();

Checkbox One = New Checkbox ("One", False, CBG);

Checkbox TWO = New Checkbox ("Two", False, CBG);

CheckBox Three = New Checkbox ("Three", True, CBG);

One.Additemlistener (this);

Two.additemlistener (this);

Three.Additemlistener (this);

F.Add (one);

F.Add (TWO);

F.Add (three);

10.3.4 drop-down list (Choice)

The drop-down list component provides a simple "select a" input from the list. E.g:

Frame f = new frame ("choice");

Choice c = new choice ();

C.ADD ("first");

C.ADD ("Second");

C.Add ("third");

C.Additemlistener (this);

F.Add (c);

When you click the drop-down list component, it displays a list, and the list contains all entries. Note that the added entries are String objects.

The ItemListener interface is used to observe the change of the drop-down list component, which is the same as the check box.

10.3.5 Canvas (Canvas)

The canvas provide a space for blank (background color). Unless you use setsize () explicitly define its size, it is 0 × 0. The space of the canvas can be used to draw, display text, receive input of keyboard or mouse. The back module will tell you how to draw in AWT.

Typically, the canvas is used to provide a general drawing space or provide a work area for the client component.

The canvas can "monitor" all events suitable for one normal component. In particular, you may also want to add Keylistener, MouseMotionListener, and MouseListener objects to allow some way to respond to user input.

Note - If you want to receive a keyboard event in the canvas, you must call the requestfocus () method of the canvas. If this step is missing, it is generally not possible to "guide" canvas. The keyboard event will be sent to another component, or it is lost throughout. Sample Code Overleaf (page 228) shows this.

Here is an example of the canvas. For each key, this program changes the color of the canvas.

Import java.awt. *;

Import java.awt.event. *;

Import java.util. *;

Public Class Mycanvas Extends Canvas

Implements keylistener {

Int index;

Color colors [] = {color.red, color.green, color.blue};

Public void paint (graphics g) {

g.setColor (Colors [Index]);

G.fillRect (0, 0, getSize (). width, getsize (); height);

}

Public static void main (string args []) {

Frame f = new frame ("canvas");

Mycanvas mc = new mycanvas ();

F.Add (MC, BorderLayout.center);

F.setsize (150, 150);

mc.RequestFocus ();

Mc.AddKeylistener (MC);

F.setVisible (TRUE);

}

Public void keytyped (KeyEvent EV) {

INDEX ;

IF (index == colors.length) {

INDEX = 0;

}

Repaint ();

}

Public void keypressed (KeyEvent EV) {

}

Public void keyreleased (KeyEvent EV) {

}

}

10.3.6 Tags (Label)

A tag object displays a row of static text. The program can change the text, but the user cannot change. The label does not have any special borders and decorations.

Label L = New Label ("Hello");

Add (L);

The label is usually not processed, but it can also be handled in the same way as the canvas. That is, the clicking event can be reliably checked only after the requestfocus () method is called.

10.3.7 Text Field (TextField)

The text domain is a single line of text input device. E.g:

TextField f = New TextField ("Single Line", 30);

F.AddActionListener (this);

Add (f);

Because only one line is allowed, the ActionListener can know this event via ActionPerformed () when you press Enter or Return. You can also add other component listeners if needed.

In addition to register an ActionListener, you can also register a TextListener to receive notifications about individual keystrokes. Its callback method is TextValueChanged (TextEvent). 10.3.8 TextArea

The text area is a multi-column text input device. You can set it to read-only with setDitable (boolean). The text area will display horizontal and vertical scroll bars.

The following example creates a 4-row × 30 character text, which initially contains "Hello!".

Textarea T = New Textarea ("Hello!", 4, 30);

T.AddTextListener (this);

Add (t);

The listener you specified with AddTexListener will receive a notification on the keystroke in the same way as the text domain.

You can add a general component listener to the text area, however, since the text is multi-line, pressing the Enter key will result in another character to buffer. If you need to identify the "End of Enter", you can place an "app" or "confirm" button next to the text area so that the user indicates "the end of the input".

10.3.9 Text Components

Text component

- Text area and text domain are subclasses

- Text component implements TextListener

Documents in text areas and text domains are divided into two parts. If you look for a class named text component, you will find a number of texts and text domains. For example, text areas and text domains are subclasses of text components.

You already know the constructor of the text area and text domain class allows you to specify the number of columns used. Remember that the displayed component is determined by the layout manager, so these settings may be ignored. Further, the number of columns is calculated according to the average width of the font used. If a spatial proportional font is used, the number of characters actually display may differ.

Since the text component implements TextListener, such as text domain, text area, and other subclasses have built-in support for keystroke events.

10.3.10 List (LIST)

A list is displayed in one area in a list so that several entries can be seen at the same time. The list can be scrolled and support radio and multiple modes. E.g:

List L = New List (4, true);

1.Add ("Hello");

1.Add ("there");

1.Add ("How");

1.Add ("are");

The numerical parameters of the constructor define the list height of the list of visible columns. This value may also be overwritten by the layout manager. A Boolean parameter for a value True indicates that this list allows the user to make multiple selections.

When you select or cancel an entry, AWT sent an instance of an item to a list. When a user double-click an entry in the scroll list, the list of radio mode and multi-selection mode generates an ActionEvent. Determine whether the entries in the list are selected based on the conventions of each platform. For UNIX / MOTIF environments, click an entry in the list of entries, only double-click the list event (selecting entry).

10.3.11 dialog box (DIALOG)

The dialog assembly is associated with a framework. It is a free window with some decorations. It is different from the framework that some of the decorations provided, and you can generate a "mode" dialog that will store all windows before being turned off.

The dialog can be unmatched and mode. For non-Mode dialogs, users can simultaneously interact with the framework and dialog box. The Mode dialog box will block all other applications of the frame before being turned off.

Since the dialog is a subclass of the window, its default layout manager is Border Layout.

Dialog D = New Dialog (F, "DIALOG", FALSE);

D. AD (New Label ("Hello, I'm A Dialog", Border.Layout.center); D.PACK ();

The dialog is usually invisible when creating. The dialog is typically displayed when a user input to a user is pressed.

Public void actionPerformed (ActionEvent EV) {

D.SetVisible (TRUE);

}

Note - You can use the dialog as a reusable device. That is to say, close the dialog box is displayed, and this object is not destroyed; save this object for later use. The garbage collection station makes a waste of memory very easy to deal with. Remember, creating and initializing objects, so you should not be created and initialized without considering.

To hide the dialog box, you must call SetVisible (false). Typical approach is to add a WindowListener to it and wait for the listener's WindowClosing (). This is parallel to handle the closure of a frame.

10.3.12 File dialog (File Dialog)

The file dialog is an implementation of the file selection device. It has its own free window, as well as window elements, and allows users to browse the file system, and select a specific file for future operations. E.g:

FileDialog D = New FileDialog (PARENTFRAME, "FileDialog");

D.SetVisible (TRUE); // block here until ok selected

String fname = d.getfile ();

Usually do not need to handle events for FileDialog. Call SetVisible (TRUE) will block the event until the user selects OK, and the user selection file name will be requested. This information will be returned as a string.

10.3.13 Rolling Panel (Scroll PANE)

The scroll panel provides a universal container that cannot be used as a free window. It should always be associated with a container (eg, a frame). It provides a window of a larger area and the scroll bar for manipulating this window. E.g:

Frame f = new frame ("scrollpane");

PANEL P = new panel ();

Scrollpane sp = new scrollpane ();

P.SetLayout (New GridLayout (3, 4));

Sp .Add (p);

F.Add (SP, "Center");

F.setsize (200, 200);

F.Servisible (TRUE);

The scroll panel creates and manages the scroll bar and holds a component. You can't control the layout manager used. You can add a panel to the scroll panel, configure the layout manager of the panel and place your components in that panel.

Typically, you don't process events on the scroll panel; these events are processed by the components contained in the scroll panel.

Section 4 menu

Menus

Must be added to the menu manager.

Including a help menu

Sethelpmenu (Menu)

There is an important difference from the menu with other components: You cannot add a menu to a general container, and you cannot use the layout manager to lay out. You can only add menu to a menu container. However, you can add a JMenusWing component to a JCONTAINER. You can start a menu "tree" by using the setmenubar () method to place the menu in a framework. From that moment, you can add the menu to the menu bar and add the menu or menu item to the menu.

The pop-up menu is an exception because they can appear in the form of floating windows, so there is no need to layout.

10.4.1 Help menu

One feature of the menu bar is that you can specify a menu as the Help menu. This can be done with sethelpmenu (menu). To help menu menu must be added to the menu bar; then it will be processed in the same manner as the help menu of the local platform. For X / Motif type systems, this involves placing the menu bar to the far right of the menu bar. 10.4.2 MenuBar

A menu module is a horizontal menu. It can only be added to a frame and become the root of all menu trees. At one moment, a frame can display a menu bar. However, you can modify the menu strip according to the status of the program, so you can display different menus at different times. E.g:

Frame f = new frame ("menubar");

MenuBar MB = New Menubar ();

F.SetMenubar (MB);

The menu bar does not support the listener. As part of the normal menu behavior, the expected events that occur in the area of ​​the menu strip are automatically processed.

10.4.3 menu

The menu component provides a basic drop-down menu. It can be added to a menu bar or another menu. E.g:

MenuBar MB = New Menubar ();

Menu m1 = new menu ("file");

Menu M2 = New Menu ("Edit");

Menu M3 = New Menu ("Help");

Mb.Add (m1);

Mb.Add (m2);

Mb.sethelpmenu (m3);

F.SetMenubar (MB);

Note - The menu shown here is empty, which is the look of the File menu.

You can join an ActionListener to the menu object, but this practice is rare. Normally, the menu is used to display and control the menu strip, which will be discussed later.

10.4.4 Menu item (MenuItem)

The menu item component is the text "leaf" node of the menu tree. They are usually added to the menu to form a complete menu. E.g:

Menu m1 = new menu ("file");

Menuitem Mi1 = New Menuitem ("New");

Menuitem Mi2 = New Menuitem ("LOAD");

Menuitem Mi3 = NewMenuItem ("Save");

Menuitem MI4 = New Menuitem ("quit");

Mi1.AddActionListener (this);

Mi2.addactionListener (this);

Mi3.AddActionListener (this);

m1.add (mi1);

m1.add (mi2);

m1.addseparator ();

m1.add (mi3);

Typically, an ActionListener is added to a menu item to provide the behavior of the menu.

10.4.5 CheckBoxMenuItem

The check menu item is a check-in menu item, so you can have an option ("On" or "Off" on the menu). E.g:

Menu m1 = new menu ("file");

Menuitem Mi1 = New Menuitem ("Save");

CheckBoxMenuItem Mi2 =

New CheckBoxMenuItem ("Persistent");

Mi1.Additemlistener (this);

Mi2.Additemlistener (this);

m1.add (mi1);

m1.add (mi2);

The check menu should be monitored with the itemListener interface. Therefore, when the check box status changes, the itemStateChanged () method is called. 10.4.6 Pop-up menu (POPUPMENU)

The pop-up menu provides a separate menu that can be displayed on any component. You can add menu entry and menu to the pop-up menu.

E.g:

Frame f = new frame ("popupmenu");

Button B = New Button ("Press Me");

POPUPMENU P = New Popupmenu ("Popup");

MenuItem S = New Menuitem ("Save");

Menuitem L = New Menuitem ("LOAD");

B. ADDACTIONLISTENER (THIS);

F.Add (B, Border.Layout.center);

P.Add (s);

P.Add (L);

F.Add (p);

To display the pop-up menu, you must call the display method. A reference that requires a component is displayed as the starting point of the X and Y axes. Typically, you have to use the components of the trigger for this purpose. In this example, the trigger is Button B.

Pop-up menu (continued)

Public void actionPerformed (ActionEvent EV) {

P.SHOW (B, 10, 10); // Display Popup

// at (10, 10) Relative to B

}

Note - The pop-up menu must be added to a "parent" component. This is different from the addition of components to the container. In this example, the pop-up menu is added to the surrounding frame.

Section 5 Control appearance

Control appearance

colour

l setForeground ()

l getForeground ()

Font

l setFont () method can be used to control the color of the displayed text.

l Dialog, Helvetica, Palatino Roman and Courier are valid font names.

You can control the foreground background color, background color and fonts of text displayed in the AWT component.

10.5.1 color

There are two ways to set the color of the component:

- setForeground ()

GetForeground ()

Both methods have a parameter, the parameter is an instance of the Java.awt.color class. You can use constant color, such as color.red, color.blue, and so on. All predefined colors columns in the document of the Color class.

In addition, you can create a specific color, for example:

INT R = 255, g = 255, b = 0;

Color C = New Color (R, G, B);

The above constructor creates a color based on the designated red, green, and blue brightness (their ranges of 0 to 255).

10.5.2 font

The font used in the assembly can be set with the setFont () method. The parameters of this method should be an example of the Java.awt.Font class.

There is no constant for the font, but you can create a font based on the name, style, and pound value of the font.

Font f = New font ("Timeesroman", Font.Plain, 14);

A valid font name includes:

- Dialog

- Helvetica

- TimeSroman

- Courier

A complete list can be obtained by calling the getFontList () method of the Toolkit object. The GetToolkit () method is used to get Toolkit after displaying Toolkit. There is another way to use the default Toolkit, which can be obtained by calling Toolkit.GetDefaultToolkit (). The font style constant is actually an int value, namely:

- Font.Bold

- font.italic

- Font.Plain

- font.bold font.italic

The pound value must be specified using the int value.

Section 6 Print

print

l In order to allow the use of local printers, the method in the following example must be used:

Frame f = new frame ("Print Test");

Thatkit t = f.gettoolkit ();

2.PrintJob Job = T.GetPrintJob (f, "MyPrintJob", NULL);

3.Graphics g = job.getgraphics ();

l Get a new graphic for each page, use:

F.PrintComponents (G);

The print processing mode and screen display in JDK1.2 are almost parallel. A special java.awt.graphics object is obtained so that any drawing instructions sent to the graphically will actually be sent to the printer.

JDK1.2 printing system allows control of the local printer to be used. When you select a print operation, the user will see a printer selection dialog. The user can then set various options, such as paper size, print quality, which printer that is used. E.g:

Frame f = new frame ("Print Test");

Toolkit t = f.gettoolkit ();

PrintJob Job = T.GetPrintJob (f, "myprintjob", null);

Graphics g = job.getgraphics ();

These codes create a Graphics object that will connect to the user selected printer.

You can use any Graphics class drawing method to use the printer. Another method, as shown below, you can let a component draw itself on the graph.

F.PrintComponents (G);

The Print () method makes the component in this way, but it is only associated with the required components. If it is a container, you can use the PrintComponents () method to draw the container and all of the components it contains in the printer.

g.dispose ();

Job.end ();

After creating an output page, use the Dispose () method to submit the page to the printer job object.

After completing the job, call the end () method of the print job object. This indicates that the print job has been completed and allows you to print a fake offline system running job, and the printer is released for other jobs.

Exercise

Exercise Goals - In this exercise, you will create a complex application that uses many components.

First, ready

In order to complete this exercise very well, you must understand the purpose of AWT, its event processor, and its graphical features.

Second, the task

Level 1: Create a drawing program layout

1. Use a java.awt package to create a Java application -PaintGui.java, which will add the components displayed in the figure below.

2. Using the Help menu dialog box.

Horizontal 3: Creating a drawing program

1. Create a simple drawing program in the above-in-picture layout. Contains a PaintHandler class that uses GUI; use event processing to complete this goal.

2. When selecting the print menu option, use java.awt.printJob to print the created graphics. Third, practice summary

Discuss - spend a few minutes to discuss, you have experienced, and what you have found in this experimental exercise process.

l Experience interpretation summary application

Fourth, check your progress

Before entering the next module, please confirm that you can:

- Know key AWT components

- Using AWT components to create a user interface for real programs

- Control the color and fonts used by the AWT components

- Using Java printed mechanism

V. Thinking

How can I get AWT to work better?

转载请注明原文地址:https://www.9cbs.com/read-8101.html

New Post(0)