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

Java Programming for absolute beginner- P14 potx

20 271 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 408,17 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 Layout ManagersIn Chapter 6, “Creating a GUI Using the Abstract Windowing Toolkit,” you used the FlowLayoutlayout manager to lay out your components.. In this chapter, you learn mo

Trang 1

Telling the Story: Creating the MadLib

Game Frame

The MadLib.java program uses a MadDialog object to retrieve user input The MadLibclass extends Frame It listens for when the user closes the MadDialog dia-log box and then builds the story and displays it in its un-editable TextArea The MadDialog Frameitself will remain hidden until after the story is already built Here’s why The MadDialogobject is modal and it is shown first by calling dia-log.setVisible(true) It will maintain focus until it is hidden again When the user clicks the x on the MadDialogwindow, the buildStory()method is called before the dialog is actually closed Once the story is done, the MadDialogwill dis-appear and the MadLibwill display the completed story

The buildStory()method itself works by creating an array of Strings that rep-resent segments of the story that break where words should be inserted The String[] getStringArray()method defined in the MadDialogclass returns the String array sorted in the order they should be inserted into the story This makes the two arrays’ indices correspond with each other, so they are processed

in a forloop to build the story Here is the source for MadLib.java

/*

* MadLib

* A MadLib game

*/

import java.awt.*;

import java.awt.event.*;

public class MadLib extends Frame implements WindowListener { private TextArea display;

private MadDialog dialog;

public MadLib() { super(“MadLib Game”);

display = new TextArea(““, 7, 60, TextArea.SCROLLBARS_VERTICAL_ONLY);

display.setFont(new Font(“Timesroman”, Font.PLAIN, 16));

display.setEditable(false);

add(display);

addWindowListener(this);

setLocation(100, 150);

pack();

dialog = new MadDialog(this);

dialog.addWindowListener(this);

dialog.setLocation(150, 100);

dialog.setVisible(true);

setVisible(true);

}

218

J a

s o

l ut

n e

Trang 2

public static void main(String args[]) { MadLib ml = new MadLib();

} private void buildStory() { String story = ““;

String[] segs = {“One fine “, “ night, a “, “ named “,

“ “, “ had a dream It was the “, “ “, “ dream since “,

“ dreamt that a “, “ “, “ “, “ and “, “ on a “, “ “,

“ In this dream, an old “, “ said to him, \””, “\” “, “ “,

“ interpreted this as a sign To “, “, it meant, “, “ “, “ “,

“ your “, “ “, “ a “, “ when the moon is “, “.” };

String[] s = dialog.getStringArray();

for (int i = 0; i < s.length; i++) { story += segs[i] + s[i];

} story += segs[segs.length - 1];

display.setText(story);

} public void windowClosing(WindowEvent e) {

if (e.getSource() == this) { dispose();

System.exit(0);

} else if (e.getSource() instanceof Dialog) { buildStory();

((Dialog)e.getSource()).setVisible(false);

} } // the rest of them that must be declared public void windowActivated(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } public void windowOpened(WindowEvent e) { } }

Summary

In this chapter, you learned all about GUI programming and Java’s AWT You learned about Containersand Components You learned how to create a Frameand add components to it You also learned how to close a Framewhen the user clicks the close box You learned about these specific components: Label, Button, TextField, TextArea, Choice, List, Checkbox, Canvas, Menu, PopupMenu, Panel,

219

i n

i n

Trang 3

Scrollbar, and Dialog In the next chapter, you learn about layout managers, GUI event handling, and simple graphics programming

220

J a

s o

l ut

n e

C H A L L E N G E S

1 Create a Frame that has many different Component s in it similar to Figure 6.2 Hint: See ComponentTest.java on the CD.

2 Go back and try playing around with some of the methods that appeared in tables of this chapter, but never actually made it into any of the programs

to see how their effects look.

Trang 4

In the last chapter, you learned about GUI programming You learned how to create components such as Button s,

TextField s, Label s, and the like In this chapter, you learn how to use layout managers to have more control over the

placement of your components Layout managers are

classes that define where and how to place components within a container You will also learn about event handling.

In a GUI, users interact with the components Event handling

describes the process of knowing when a user interacts with a component and then causing some action to occur based on the user’s actions By the end of this chapter, you will be able to use layout managers and event handling to create a more advanced version of the MadLib game, cre-ated in the previous chapter This chapter covers the follow-ing AWT concepts:

Use layout managers

Handle GUI events

Advanced GUI: Layout Managers

and Event Handling

7

C H A P T E R

Trang 5

The Project: the AdvancedMadLib

Application

This application has the same goal as the MadLibproject from the previous chap-ter, which is to provide a graphical interface for the users to enter specific types

of words and generate nonsensical output using those words within a story How-ever, it accomplishes it much differently There are some more advanced features

that make it more user-friendly The term user friendly describes an interface that

the user can easily understand and use to accomplish the desired task

When the AdvancedMadLib application starts, a window entitled “Create your own Song” opens In this chapter, you make this MadLibtake the form of a song The window has a label “Enter some nouns:” and then has some TextField prompts for the user to enter some nouns There are also some Buttons on the bottom—Prev, Next, and Show/Refresh Story—and a Choice with the options Nouns, Verbs, and Other These components on the bottom of the Advanced-MadLib Frame are used for navigating the input Panels The entire application consists of three panels used for entering nouns, verbs, and other text, and also

a Framethat displays the story based on the user’s input Figure 7.1 displays the Nouns panel and the completed story

Here’s how it works The user first enters the nouns, and then clicks the Next button to get to the screen that allows the entry of the verbs Once the verbs are entered, the user clicks Next again to get to the screen that allows entry of other text such as nicknames, adjectives, prepositions, and so on Once all input is completed, the user clicks the Show/Refresh Story button to display the new #1 hit song

The AdvancedMadLibapplication is actually more versatile than that The users can click the Prev button to go back to a previous screen to enter some text they might have missed, or just want to edit The Choicealso allows users to go to any

of the three screens instantly by selecting from Nouns, Verbs, or Other choices The Show/Refresh Story button is also more versatile The user initially clicks it

to display the story in a second window, but the original input window stays open The users can then make any edits to the TextFields and then click the but-ton again to refresh the story to reflect the changes Also, the users can close the window that contains the song (entitled “Your Song”) and then reopen it by click-ing the Show/Refresh Song button All in all, it’s a much better MadLib applica-tion interface

222

J a

s o

l ut

n e

Trang 6

Using Layout Managers

In Chapter 6, “Creating a GUI Using the Abstract Windowing Toolkit,” you used the FlowLayoutlayout manager to lay out your components In this chapter, you learn more about the FlowLayoutlayout manager as well as some other layout managers Layout managers are classes that implement the LayoutManager inter-face of the java.awtpackage and describe where and how your GUI application should put its components relative to the other components

For example, if you created a frame and added six buttons to it, the layout man-ager would be responsible for knowing where, within that frame, to place those buttons and how to handle their placement when the frame is resized When adding a great deal of components to your containers, it is essential to use layout managers to facilitate the programmatic description of the design of your GUI

Using FlowLayout

The FlowLayoutlayout manager is the simplest of all the layout managers It sim-ply arranges the components you add to the container, in the order that you add them, from left to right, and wraps them onto a new line when it runs out of room You can think of this as being similar to how your word processor wraps

223

FIGURE 7.1

The

AdvancedMadLib

application creates

a song by using the text entered by the users.

Trang 7

words within a paragraph By default, each “line” of components is centered, but you can specify left, right, or center alignment The FlowLayoutTestapplication shows you how to use the FlowLayoutlayout manager Here is the source code: /*

* FlowLayoutTest

* Demonstrates use of the FlowLayout layout manager.

*/

import java.awt.*;

import java.awt.event.*;

public class FlowLayoutTest extends Frame

implements WindowListener { public FlowLayoutTest() {

super("FlowLayout Test");

addWindowListener(this);

setLayout(new FlowLayout(FlowLayout.RIGHT, 20, 50));

for (int b=1; b <= 15; b++) { add(new Button("Button " + b));

} setSize(575, 300);

setVisible(true);

} public static void main(String args[]) { new FlowLayoutTest();

} //WindowListener Interface public void windowClosing(WindowEvent e) { dispose();

System.exit(0);

} public void windowOpened(WindowEvent e) {}

public void windowActivated(WindowEvent e) {}

public void windowDeactivated(WindowEvent e) {}

public void windowIconified(WindowEvent e) {}

public void windowDeiconified(WindowEvent e) {}

public void windowClosed(WindowEvent e) {}

}

As in all the layout manager examples in this chapter, the FlowLayoutTest appli-cation extends Frameand implements WindowListener, so it is a Frame You can close it normally because the windowClosing(WindowEvent) method is imple-mented If you are unsure how to create a Framethat implements the WindowLis-tenerinterface, review Chapter 6, as this chapter builds on that information

224

J a

s o

l ut

n e

Trang 8

Okay, so here the Frame is created and its setLayout(LayoutManager) method, inherited from the Containerclass, is called The argument to that method is new FlowLayout(FlowLayout.RIGHT, 20, 50) This instantiates a new FlowLayoutso that the “lines” of components are right aligned (because of the first static int argument FlowLayout.RIGHT) The second and third arguments are the horizon-tal and vertical gap arguments, respectively They specify the horizonhorizon-tal and ver-tical pixel distance between components

You can see the three FlowLayout constructor methods in Table 7.1 The align-ment constants shown in Table 7.1 are pretty self-explanatory except for FlowLay-out.LEADING and FlowLayout.TRAILING FlowLayout.LEADING specifies that the components are justified from the leading edge of the container What this means is that if the container is oriented left-to-right, the left side is the leading edge If the container is oriented right-to-left, the leading edge is the right side

FlowLayout.TRAILINGspecifies that the components are justified from the trail-ing edge of the container, as you might have deduced

225

FlowLayout() Constructs a FlowLayout with a default center alignment

and a five-pixel horizontal and vertical gap.

FlowLayout(int) Constructs a FlowLayout with the specified alignment (can

be one of the following: FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT, FlowLayout.LEADING, or FlowLayout.TRAILING).

FlowLayout(int, int, int) Constructs a FlowLayout with the specified alignment and

horizontal and vertical component gaps.

T A B L E 7 1 F L O W L A Y O U T C O N S T R U C T O R M E T H O D S

In the forloop, 15 buttons are created and added to the Frame The fact that the layout manager was set to FlowLayoutbeforehand lets the Frameknow where to put them You can see the output of the FlowLayoutTestapplication in Figure 7.2

When you run this application, resize the window so you can see how the

FlowLayoutlayout manager repositions the buttons based on different window sizes

Using GridLayout

The GridLayoutclass lays out its components in a grid of equally sized rectangu-lar cells You just need to specify the number of rows and columns and then add the components The GridLayoutlayout manager adds the components from left

Trang 9

J a

s o

l ut

n e

FIGURE 7.2

The

FlowLayoutTest

application lays out

15 buttons, right aligned, using the

FlowLayout layout manager.

to right in rows When it reaches the end of a row, it creates a new row and adds columns in that row from left to right Here is an example of a GridLayoutthat lays out 12 buttons in a grid of four rows by three columns It also sets a hori-zontal gap of five and a vertical gap of 10 pixels in between components:

/*

* GridLayoutTest

* Demonstrates the GridLayout layout manager

*/

import java.awt.*;

import java.awt.event.*;

public class GridLayoutTest extends Frame

implements WindowListener { public GridLayoutTest() {

super("GridLayout Test");

addWindowListener(this);

setLayout(new GridLayout(0, 3, 5, 10));

for (int b=1; b <=12; b++) { add(new Button("Button " + b));

} pack();

setVisible(true);

} public static void main(String args[]) { GridLayoutTest glt = new GridLayoutTest();

} //WindowListener Interface public void windowClosing(WindowEvent e) { dispose();

System.exit(0);

} public void windowOpened(WindowEvent e) {}

public void windowActivated(WindowEvent e) {}

Trang 10

public void windowDeactivated(WindowEvent e) {}

public void windowIconified(WindowEvent e) {}

public void windowDeiconified(WindowEvent e) {}

public void windowClosed(WindowEvent e) {}

} Figure 7.3 shows how the GridLayoutlayout manager lays out the buttons created

in the GridLayoutTest application and Table 7.1 summarizes the GridLayout class constructor methods

When you create a new GridLayout object, you can specify both the number of rows and the number of columns, but you can also just specify one or the other.

For example, if you wanted to create a layout that had three columns and any number of rows, you can specify the number of columns to be three and the num-ber of rows to be zero.

setLayout(new GridLayout(0, 3));

Java interprets this as meaning that there are strictly three columns, but there can be any number of rows You cannot specify zero for both rows and columns

at the same time.

T R I C K

227

FIGURE 7.3

The GridLayout

manager has rows and columns of equal sized components.

GridLayout() Constructs a GridLayout with a default of one row of

components.

GridLayout(int, int) Constructs a GridLayout with the given number of

rows and columns.

GridLayout(int, int, int, int) Constructs a GridLayout with the given number of

rows and columns The third and fourth arguments are the horizontal and vertical spacing in between components.

T A B L E 7 2 G R I D L A Y O U T C O N S T R U C T O R M E T H O D S

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

TỪ KHÓA LIÊN QUAN