1. Trang chủ
  2. » Công Nghệ Thông Tin

Java Programming for absolute beginner- P12 pdf

20 401 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 20
Dung lượng 373,75 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Using FramesThe Frame class is a GUI component that defines a top-level window.. Remember also that Frame inherits from the Component class, so the methods shown in Table 6.1 are also pr

Trang 1

Using Frames

The Frame class is a GUI component that defines a top-level window A Frame includes a border and a title bar The Frameclass extends the Windowclass, which

is a top-level window without a border or title bar The Windowclass subclasses the Container class, which is a component that can contain other components Because Frameinherits from these other classes, it is itself a container able to hold other components Table 6.2 summarizes some of the Frameclass’s methods Remember also that Frame inherits from the Component class, so the methods shown in Table 6.1 are also present in the Frameclass

The UselessFrame Application

The UselessFrameclass extends the Frameclass and doesn’t do much except set its size and display it To write this application, first you must import the Frame class:

import java.awt.Frame;

Then you declare the UselessFrameclass and indicate that it is a subclass of the Frameclass:

public class UselessFrame extends Frame {

178

J a

s o

l ut

n e

resized by the users.

T A B L E 6 2 S U M M A R Y O F F R A M E M E T H O D S

Trang 2

Frames are initially not visible and are automatically sized to their minimum size, which is quite small So small, in fact, that you might not even notice them once they are displayed in the upper-left corner of your screen The constructor takes care of creating a new UselessFramewith the title, Useless Frame, by call-ing its superclass’s Frame(String)constructor Then it sets the size to 300pixels wide by 200pixels high, by calling the setSize(300, 200)method defined in the Component class Finally, the constructor shows the UselessFrame by calling setVisible(true) The main() method simply instantiates a new UselessFrame because the constructor takes care of the rest The source code for Useless-Frame.javais listed here:

/*

* UselessFrame

* A Frame that does absolutely nothing aside from merely existing

*/

import java.awt.Frame;

public class UselessFrame extends Frame { public UselessFrame() {

super(“Useless Frame”);

setSize(300, 200);

setVisible(true);

} public static void main (String args[]) { UselessFrame uf = new UselessFrame();

} } When you run this at the command prompt by typing java UselessFrame, a win-dow will pop up with the title Useless Frame You can see the window in Figure 6.3 I ran this from a Microsoft Windows 98 environment at a screen resolution

of 800×600 Your window might look different if you ran it from a different oper-ating system and/or screen resolution The UselessFrameinitially appears in the top-left corner of the computer screen, but I moved it by clicking the title bar and dragging it to a new location before I created the screen shot When you run this you can go ahead and play around with it Move it, minimize it, maximize it, deactivate it by clicking another window or on the desktop, reactivate it by click-ing it, and so on The one thclick-ing you can’t do is close the window by clickclick-ing the

x That’s because you haven’t handled the window-closing event yet You do this

in the next section

When you create a window that won’t close, or any Java program that hangs without any activity, try pressing Ctrl+C at the command prompt to stop the

pro-T R I C K

179

i n

i n

Trang 3

can try is pressing Ctrl+Alt+Delete to end the task from the task manager Be careful when using Ctrl+Alt+Del because after you press this combo once, pressing it again will cause your computer to reboot and you will lose any unsaved files.

180

J a

s o

l ut

n e

FIGURE 6.3

This is an example

of a frame that does nothing other than display itself.

Learning about Containers

The Containerclass defines a Componentthat can contain other Components The

Containermaintains a list of the Components it contains You can add Components

to it by calling its add(Component)method Containers arrange their Components

by using a layout manager Layout managers are fully covered in Chapter 7, but

in this chapter you do use the FlowLayoutclass, the simplest of the layout man-agers in this chapter to display multiple Components within a Frame

Using the WindowListener Interface

The WindowListenerinterface handles WindowEvents The UselessFramewindow doesn’t close when you click the close button because it does not implement the

WindowListenerinterface When you implement this abstract interface in your classes, you are required to define all the following methods:

public void windowClosing(WindowEvent) public void windowActivated(WindowEvent) public void windowClosed(WindowEvent) public void windowIconified(WindowEvent)

Trang 4

public void windowDeiconified(WindowEvent) public void windowDeactivated(WindowEvent) public void windowOpened(WindowEvent) These methods are defined in Chapter 7 In this chapter, you are only interested

in the windowClosing(WindowEvent)method This is what is called when the user clicks your window’s close button to close it They are all listed here because you have to define them in the ComponentTestFrameclass because you want to be able

to use the interface to actually close the window without having to manually intervene and halt your program

The ComponentTestFrame class extends Frame and implements the WindowLis-tenerinterface How do you get it to do that? You just tell it the way it is:

public class ComponentTestFrame extends Frame implements WindowListener { You use the extendsword normally, followed by the superclass, Frame, and then you follow that with another keyword implementsand the interface, WindowLis-tener As soon as you do this, you know that you have to define the methods shown previously Take a look at the source code for ComponentTestFrame.java and then make sure you take the time to write it out and compile it You need to use it throughout the rest of this chapter

/*

* ComponentTestFrame

* A Simple Frame to use for testing components

*/

import java.awt.*;

import java.awt.event.*;

public class ComponentTestFrame extends Frame

implements WindowListener { public ComponentTestFrame(String title) {

super(title);

setBackground(SystemColor.control);

setSize(400, 300);

setLocation(200, 150);

setLayout(new FlowLayout());

addWindowListener(this);

} // the only WindowListener method I care about public void windowClosing(WindowEvent e) { dispose();

System.exit(0);

} // the rest of them that must be declared public void windowActivated(WindowEvent e) { }

181

i n

i n

Trang 5

public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } public void windowOpened(WindowEvent e) { } }

The only method you care about here is the windowClosing(WindowEvent) method, so that’s the only one you need to add statements to You add two state-ments to the body of this method that take care of closing the window and exit-ing the program dispose() releases the native resources owned by the Frame and those of its components as well (closes and disposes of the window’s resources) The System.exit(0) statement terminates the program itself The rest of the WindowListenermethods are there only because you have to define them In this case, you don’t add any statements in the methods, so they don’t actually do anything

The WindowListener interface is defined within the java.awt.event package,

so you need to import that package It also defines the WindowEvent class When you import a package using the asterisk character * , it indicates that only those classes that are referenced within the program should be imported Actually, nothing is imported into the object code; remember that the import statement just indicates where to find the classes you’re using.

This ComponentTestFramecomponent performs some other operations of interest

as well It sets its background color to SystemColor.control, which is the back-ground color currently set for your operating system’s control objects, such as windows, dialog boxes, buttons, and so on This color is not the default color for Frames; however, so you need to set it explicitly if you want it to have that partic-ular background color It also sets its location to the (x, y) pixel coordinates (200,

150) and sets its layout to FlowLayout Basically, this layout manager lays its Com-ponents out in a center-aligned row (by default) until there is no more room, and then wraps around to the next row and continues to do this until there are no more Componentsto align

Using Components

In this section, you test the AWT Components by adding them to a ComponentTest-Frameinstance of the class you defined in the previous section Because the lay-out is already set to FlowLayout, you create the Components and then add them to the ComponentTestFrame, using the add(Component)method You learn about the different specifics of these Components by creating multiple instances of the same Componentusing different states You then call different methods and compare their appearances and behaviors

T R I C K 182

J a

s o

l ut

n e

Trang 6

The Label Component

A Labelcontains read-only text that you display within a container Like all other Components, you can change its background and foreground colors You can also set the alignment of text within the Label’s area Table 6.3 shows some of the more common fields and methods of the Labelclass

In the LabelTestprogram, you use the ComponentTestFrameto display four dif-ferent Labels You create the l1object by using the Label(String)constructor, which builds a Labelwith the given Stringthat is left aligned by default The l2 label demonstrates that the font can be changed using the setFont(Font) method You use the Label()constructor with no arguments to construct the l3 Label, and then set the text using the setText(String) method and also call setEnabled(false)to disable the Label As you can see in Figure 6.4, the graph-ics for a disabled Labelare grayed out The l4 Label’s foreground color is set to green and the background color is set to black Its text is right-aligned because the constructor was called using Label.RIGHT

Next, you create the ComponentTestFrame Because that class itself does most of its own work, you only need to create a ComponentTestFrameobject, frame, by pass-ing a Stringtitle to its constructor After you do that, you can add the Label com-ponents you created earlier by calling frame.add(Component) and passing the labelas its Componentparameter Next, you call frame.setVisible(true)to show

183

i n

i n

Field or Method Description

alignment.

T A B L E 6 3 F I E L D S A N D

M E T H O D S O F T H E L A B E L C O M P O N E N T

Trang 7

the window and that’s all you need to do The window-closing event is already handled in the ComponentTestFrameclass itself, so you don’t have to worry about that here Notice that if you resize the window, the Labels can be realigned If you maximize the window, they will all form one row, but if you make the window narrow, the labels will all line up in one column That fact further emphasizes how the FlowLayoutlayout manager works Here is a listing of the source code: /*

* LabelTest

* Tests the Label Component

*/

import java.awt.*;

public class LabelTest { public LabelTest() { //Make the Labels Label l1 = new Label(“Label”);

Label l2 = new Label(“I am a Label”);

l2.setFont(new Font(“Timesroman”, Font.BOLD, 18));

Label l3 = new Label();

l3.setText(“I am disabled”);

l3.setEnabled(false);

Label l4 = new Label(“Colored, Right aligned”, Label.RIGHT);

l4.setForeground(Color.green);

l4.setBackground(Color.black);

//Make the Frame and add the labels to it ComponentTestFrame frame = new ComponentTestFrame(“Label Test”);

frame.add(l1);

frame.add(l2);

frame.add(l3);

frame.add(l4);

frame.setVisible(true);

} public static void main(String args[]) { LabelTest lt = new LabelTest();

} }

184

J a

s o

l ut

n e

FIGURE 6.4

Four Label s are displayed in the Component-TestFrame

Trang 8

The Fontand Colorclasses of the java.awtpackage are used here to change the font and color associated with the Labels They are used throughout this chap-ter to emphasize the flexibility you have in changing the appearance of Compo-nents The Font class defines a font face associated with a Component that is present on the system In this chapter, you use the Font(String, int, int) con-structor to build a Font The first argument is the name of the Font, and the sec-ond argument is the style of the Font, which can be Font.PLAIN, Font.BOLD, Font.ITALIC, or Font.BOLD + Font.ITALIC The third argument is the point size for the Font In this chapter you also use Colorconstants to specify colors for your Components Some of these constants are Color.black, Color.blue, Color.cyan, Color.red, and Color.yellow The Fontclass and the Colorclass are revisited in Chapter 7 when you learn about graphics programming

The Button Component

The Buttonclass defines a labeled button Buttons typically trigger some action when the user clicks them There are two constructors One accepts no arguments and just creates an empty Button You can set its labellater on using the setLa-bel(String)method The other constructor accepts a Stringargument specified

to be its label Table 6.4 shows some of the other common Buttonmethods

In the ButtonTestprogram, you create four Buttonobjects to get a feel for how to create and use the Buttoncomponent You construct b1with the Button(String)

constructor to set its label to “Button” You call the Button() constructor to instantiate the b2 Buttonobject, creating an empty Button Then you call two of its methods to set the label and change the font:

b2.setLabel(“Press me!”);

b2.setFont(new Font(“Timesroman”, Font.BOLD, 18));

185

i n

i n

text label.

T A B L E 6 4 B U T T O N M E T H O D S

Trang 9

When looking at Figure 6.5 from left to right, you can see that the font of the sec-ond Buttonis bigger, bold, and Times Roman (The first Buttonis a standard one added for comparison.) You can also see that the third Button, b3 (called “Can’t press me”), is not enabled The label is grayed out and when you actually run this, you can see that you cannot click it Disabling a Componenthas a visual and func-tional effect Its appearance is altered and the users cannot interact with it The fourth Button, b4(called “Colors”), has a different appearance than the other but-tons because you set its background color and foreground colors differently by calling its setBackground(Color)and setForeground(Color)methods Here is a listing of ButtonTest.java

/*

* ButtonTest

* Demonstrates the Button Component

*/

import java.awt.*;

public class ButtonTest { public ButtonTest() { //Make the Buttons Button b1 = new Button(“Button”);

Button b2 = new Button();

b2.setLabel(“Press me!”);

b2.setFont(new Font(“Timesroman”, Font.BOLD, 18));

Button b3 = new Button(“Can’t press me”);

b3.setEnabled(false);

Button b4 = new Button(“Colors”);

b4.setForeground(Color.green);

b4.setBackground(Color.black);

//Make the Frame and add the buttons to it ComponentTestFrame frame = new ComponentTestFrame(“Button Test”);

frame.add(b1);

frame.add(b2);

frame.add(b3);

frame.add(b4);

186

J a

s o

l ut

n e

FIGURE 6.5

This is a test of the Button component.

Trang 10

} public static void main(String args[]) { ButtonTest bt = new ButtonTest();

} } When you run the ButtonTestapplication, try traversing the buttons using Tab and Shift+Tab You can see the appearance of the Buttoncurrently in focus is dif-ferent and stands out as the one that has user input focus A Componentis said to

have focus when it is immediately ready to accept user input For instance, while

traversing through the Buttons, press the spacebar The Buttonthat currently has focus will be clicked Also take note that the disabled Buttonnever receives user input focus

The TextField Component

There are two text components in the AWT They subclass the TextComponent superclass Table 6.5 shows some of the TextComponent methods inherited by

187

i n

i n

selected text begins.

selected text ends.

positions to become selected.

is inserted).

T A B L E 6 5 T E X T C O M P O N E N T M E T H O D S

Ngày đăng: 03/07/2014, 05:20

TỪ KHÓA LIÊN QUAN