Java By Example PHẦN 6 pptx

59 227 0
Java By Example PHẦN 6 pptx

Đ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

menu, Java generates an event that you can capture in the action() method. In the case of a choice menu, action()'s first parameter is the menu instance, and the second parameter is the text of the selected menu item. By comparing the text to the items you added to the menu, you can determine which menu item the user chose. The ChoiceApplet applet, whose source code is shown in Listing 20.2, demonstrates creating and responding to choice menus in an applet. Listing 20.3 is the applet's HTML document. When you run the applet under Appletviewer, you see the window shown in Figure 20.3. The text in the window is displayed using the currently selected color in the choice menu. To change the text color, just select a new menu item. Figure 20.3 : ChoiceApplet displays text in the color selected from its choice menu. Listing 20.2 ChoiceApplet.java: Using Menus in an Applet. import java.awt.*; import java.applet.*; public class ChoiceApplet extends Applet { Choice menu; Color color; public void init() { Choice menu = new Choice(); menu.addItem("Black"); menu.addItem("Red"); menu.addItem("Green"); menu.addItem("Blue"); add(menu); color = Color.black; } public void paint(Graphics g) { Font font = new Font("TimesRoman", Font.BOLD, 24); int height = font.getSize(); g.setFont(font); g.setColor(color); g.drawString("This text is drawn in", 32, 75); g.drawString("the color selected from", 32, 75+height); g.drawString("the above choice menu.", 32, 75+2*height); } public boolean action(Event evt, Object arg) { if (evt.target instanceof Choice) HandleMenu(arg); return true; } protected void HandleMenu(Object item) { if (item == "Black") color = Color.black; else if (item == "Red") color = Color.red; else if (item == "Green") color = Color.green; else color = Color.blue; repaint(); } } Tell Java that the applet uses the classes in the awt package. Tell Java that the applet uses the classes in the applet package. Derive the ChoiceApplet class from Java's Applet class. Declare menu and color objects. Override the init() method. Create the menu object. Add commands to the menu object. Add the menu to the applet. Initialize the starting color for the text. Override the paint() method. Create and set the display font. Set the selected color. Display text in the selected color. Override the action() method. If the menu caused the event, call the HandleMenu() method. Tell Java that the event was handled okay. Declare the HandleMenu() method. Set the color field based on the menu selection. Tell Java to repaint the applet's display area. Listing 20.3 CHOICEAPPLET.htmL: ChoiceApplet's HTML Document. <title>Applet Test Page</title> <h1>Applet Test Page</h1> <applet code="ChoiceApplet.class" width=300 height=150 name="ChoiceApplet"> </applet> Scrolling Lists Whereas choice menus usually display a set of commands or options, scrolling lists are best used to display a list of items from which the user can choose. For example, you might use a scrolling list to enable the user to choose a state when filling out an address form. The scrolling list in this case would contain all 50 states. The user would only need to double-click on his or her state in order to complete that section of the form. Scrolling lists not only make it easy for users to enter information, but also ensure that the user makes a choice from a valid set of responses. To create a scrolling list, you first call the List class's constructor, like this: List list = new List(num, false); The constructor's two arguments are the number of visible lines in the list and a boolean value indicating whether the list will support multiple selections. The list created in the preceding will not allow the user to select more than one item simultaneously. When you have the list object created, you can add items to the list. You do this by calling the List object's addItem() method: list.addItem(str); Here, str is the text string for the item to add to the list. NOTE You can add as many items as you like to a list. You are not limited to the number of items given as the List constructor's first argument. That value specifies only the size of the list box; that is, the value determines how many items are visible on the screen at one time. Example: Creating a Single-Selection List Suppose that you need to create a list that contains musical artists from which the user must select only one. First, you create the list object, after which you add the names of the artists you want to include. Finally, you add the list to the applet. Listing 20.4 shows the Java code that performs these tasks. Figure 20.4 shows the resultant list box. Figure 20.4 : In this list, only one item can be selected at a time. Listing 20.4 LST20_4.TXT: Creating a Single-Selection List Box. List list = new List(10, false); list.addItem("Pearl Jam"); list.addItem("Dream Theater"); list.addItem("Joe Satriani"); list.addItem("Oasis"); list.addItem("Alanis Morissette"); list.addItem("Soul Asylum"); list.addItem("The Rembrandts"); list.addItem("Smashing Pumpkins"); list.addItem("Joan Osborne"); list.addItem("Bjork"); add(list); Because the List constructor's first argument is 10 and there are only 10 items in the list, all of the items are visible on the screen. Moreover, because the List constructor's second parameter is false, in the list created by Listing 20.4, the user can select only a single artist at a time. Example: Creating a Multiple-Selection List When you display a list of musical artists such as that created by Listing 20.4, you may want the user to select more than one. In this case, you can create a multiple-selection list, just by changing the List constructor's second argument to true, like this: List list = new List(10, true); As Figure 20.5 shows, the new list enables the user to select as many artists as he or she likes. Figure 20.5 : Now the user can select more than one artist at a time. Example: Creating a Scrolling List You may have noticed that in this chapter's title, the list controls are called "scrolling lists." So far, though, none of your lists have scrolled. In fact, they haven't even had scroll bars. Whenever the size of the list box (given as the constructor's first argument) is greater than or equal to the number of items in the list, the list doesn't need to scroll, so no scroll bar appears. However, as soon as the number of items exceeds the size of the list box, Java enables scrolling. As an example, suppose that you were to change the first line of Listing 20.4 to this: List list = new List(5, false); Now, you have a list that can display five items at a time. However, there are 10 items in your list, which means that, in order for the user to be able to see all then items, the list must scroll. Figure 20.6 shows the resultant scrolling list. Figure 20.6 : The user must scroll this list to see all the items. Methods of the List Class Because there's so much you can do with a scrolling list control, the List class has a large set of public methods that you can call to manipulate a list. The most useful of these methods are listed in Table 20.2. Although there are a lot of methods to learn in the table, the most important are addItem(), getSelectedIndex(), getSelectedIndexes(), getSelectedItem(), and getSelectedItems(). Using these five methods, you can create a basic scrolling list and enable the user to make selections from it. In the next section, in fact, you'll see how to determine which item the user selected. Table 20.2 Most Useful Methods of the List Class. Method Description void addItem(String item) Adds an item to the end of the list. void addItem(String item, int index) Adds an item to a specific position in the list. boolean allowsMultipleSelections() Returns a boolean value indicating whether the list supports multiple selection. void clear() Clears all items from the list. int countItems() Returns the number of items in the list. void delItem(int position) Deletes the item at the given position from the list. void delItems(int start, int end) Deletes a group of items from the list. void deselect(int index) Deselects the item at the given index. String getItem(int index) Returns the item at the given index. int getRows() Returns the size of the list box. int getSelectedIndex() Gets the index of the selected item. int[] getSelectedIndexes() Gets the indexes of a multiple selection. String getSelectedItem() Returns the selected item in a list. String[] getSelectedItems() Returns all the items in a multiple selection. int getVisibleIndex() Returns the index of the last item that was made visible. boolean isSelected(int index) Returns a boolean value indicating whether the item at the given index is selected. void makeVisible(int index) Ensures that the item at the given index is visible. void replaceItem(String Replaces the item at the given newValue, int index)index with a new item. void select(int index) Selects the item at the given index. void setMultipleSelections(boolean v) Toggles the multiple-selection mode. Example: Using a Scrolling List in an Applet By now, you've gotten used to working with the list of musical artists that I've used in the previous few examples. In this example, you put that list to the test by not only creating and displaying the list in an applet, but also by displaying the user's selection. Listing 20.5 is the source code for the ListApplet applet. Listing 20.5 ListApplet.java: An Applet with a Scrolling List. import java.awt.*; import java.applet.*; public class ListApplet extends Applet { List list; public void init() { list = new List(5, false); list.addItem("Pearl Jam"); list.addItem("Dream Theater"); list.addItem("Joe Satriani"); list.addItem("Oasis"); list.addItem("Alanis Morissette"); list.addItem("Soul Asylum"); list.addItem("The Rembrandts"); list.addItem("Smashing Pumpkins"); list.addItem("Joan Osborne"); list.addItem("Bjork"); add(list); resize(300, 150); } public void paint(Graphics g) { g.drawString("CHOSEN ITEM:", 100, 110); String s = list.getSelectedItem(); if (s == null) s = "None"; g.drawString(s, 100, 130); } public boolean action(Event evt, Object arg) { [...]... 21 .6 : This is CanvasApplet running under Appletviewer NOTE Often, you'll want to derive your own custom canvas class from Java' s Canvas class Then, you can more easily control what's drawn in the canvas, by overriding the canvas's paint() method This is the approach that's used in the CanvasApplet applet Listing 21.2 CanvasApplet .java: An Applet That Displays a Canvas import java. awt.*; import java. applet.*;... Scrollbar and Canvas Controls CONTENTS q q q q Scrollbars r Example: Creating a Scrollbar r Responding to a Scrollbar r Example: Using a Scrollbar in an Applet r Canvases r Example: Using a Canvas in an Applet Summary Review Questions Review Exercises Next in the long list of Java controls are the scrollbar and canvas controls, which are represented by the Scrollbar and Canvas classes Using a scrollbar,... text, but also add new text Figure 20.8 : TextAreaApplet applet run-ning under Appletviewer Listing 20 .6 TEXTAREAAPPLET .JAVA: The TextAreaApplet Applet import java. awt.*; import java. applet.*; public class TextAreaApplet extends Applet { TextArea textArea; public void init() { String s = "This is an example of a\n"; s += "textarea control, which is not\n"; s += "unlike a textfield control.\n"; s += "The... number of columns As with the other controls, after you create the TextField object, you add it to the applet by using the add() method Example: Creating a TextArea Control As an example, suppose that you need to create a TextArea control that'll start off displaying eight lines of text Listing 20 .6 is an applet, called TextAreaApplet, that creates a TextArea control that displays eight lines of text Figure... the applet in the normal way, by calling the add() method: add(panel); Example: Creating and Using Panels Using panels can be a little confusing at first, so an example is in order Suppose you need to create an applet that displays four buttons, but you don't want Java to place the buttons one after the other in the display, which Java will do with its default layout Instead, you want the buttons displayed... Finally, the TextArea control provides a simple text editor that you can easily add to your applets Review Questions 1 2 3 4 5 6 7 8 9 10 11 How many arguments are accepted by the Choice class's constructor? How do you add items to a choice menu? What are the two arguments needed by the List class's constructor? How do you add items to a scrolling list? When would you use a TextArea control in place of...repaint(); return true; } } Tell Java that the applet uses the classes in the awt package Tell Java that the applet uses the classes in the applet package Derive the ListApplet class from Java' s Applet class Declare the list object Override the init() method Create the list object Add items to the list object... size (the amount the display scrolls when the user clicks above or below the scroll box), and the minimum and maximum values represented by the scrollbar After creating the scrollbar object, you add it to the applet by calling the add() method, like this: add(scrollbar); Example: Creating a Scrollbar Suppose you need to create a scrollbar that'll enable the user to select a value from 1 to 100 You can... Scrollbar(Scrollbar.HORIZONTAL, 50, 0, 1, 100); add(scrollbar); The constructor's first argument tells Java that the scrollbar should be drawn horizontally on the display The second argument tells Java that you want the scrollbar to start off set to the value of 50 The third argument is the page size, which represents the area in the slider covered by the scroll box Finally, the fourth and fifth arguments give the scrollbar... handleEvent() method handles all the specific event messages that are generated by the typical windowing system Table 21.1 lists some of the events to which the handleEvent() method can respond Table 21.1 Most Common Events That Can Be Handled by handleEvent() Event Message Description ACTION_EVENT An event that can be handled by action() GOT_FOCUS The component received the focus KEY_PRESS A key on the . mode. Example: Using a Scrolling List in an Applet By now, you've gotten used to working with the list of musical artists that I've used in the previous few examples. In this example, . TextAreaApplet applet run-ning under Appletviewer. Listing 20 .6 TEXTAREAAPPLET .JAVA: The TextAreaApplet Applet. import java. awt.*; import java. applet.*; public class TextAreaApplet extends Applet { . created by Listing 20.4, the user can select only a single artist at a time. Example: Creating a Multiple-Selection List When you display a list of musical artists such as that created by Listing

Ngày đăng: 12/08/2014, 19:21

Mục lục

  • Java By Example

    • Chapter 21 -- Scrollbar and Canvas Controls

    • Chapter 22 -- Panels and Layout Managers

    • Chapter 23 -- Windows and Menu Bars

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan