Java Programming for absolute beginner- P13 doc

20 298 0
Java Programming for absolute beginner- P13 doc

Đ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

l3.select(9); l3.setForeground(Color.red); l3.setBackground(Color.black); l3.setFont(new Font(“Courier”, Font.PLAIN, 16)); List l4 = new List(); l4.add(“Not Enabled”); l4.add(“Nope”); l4.select(1); l4.setEnabled(false); //Make the Frame and add the Lists to it ComponentTestFrame frame = new ComponentTestFrame(“List Test”); frame.add(l1); frame.add(l2); frame.add(l3); frame.add(l4); frame.setVisible(true); } public static void main(String args[]) { ListTest lt = new ListTest(); } } 198 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r FIGURE 6.9 The List component allows the users to choose only one, or more than one, item, depending on how you set it up. The Checkbox Component Checkbox is a fairly simple component that defines one item that can be either checked or unchecked ( true or false). It has a text label used to identify it. The Checkbox class has constructors that allow you to specify its label, its state (true or false), and the CheckboxGroup it belongs to. Table 6.10 shows some of the Checkbox class’s methods. The CheckboxTest application creates some Checkbox objects. Figure 6.10 shows the output. You can select or deselect any one of these objects except for the two disabled ones (Garlic and Sugar). Note that you can also select more than one of them simultaneously. Each time the user clicks a Checkbox, its state reverses from true to false, or from false to true. JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 198 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 199 C h a p t e r 6 C r e a t i n g a G U I U s i n g t h e A b s t r a c t W i n d o w i n g T o o l k i t /* * CheckboxTest * Demonstrates the Checkbox Component */ import java.awt.*; public class CheckboxTest { public CheckboxTest() { //Make the Checkboxes Checkbox cb1 = new Checkbox(“Peppers”); Checkbox cb2 = new Checkbox(“Onions”); Method Description Checkbox() Constructs a new Checkbox object. Checkbox(String) Constructs a new Checkbox object with the given String label. Checkbox(String, boolean) Constructs a new Checkbox with the given String label and the given state (true if it is initially checked, or false if it is not). Checkbox(String, boolean, CheckboxGroup) Constructs a new Checkbox with the given String label and the given state (true if it is initially checked, or false if it is not). It is specified as a member of the given CheckboxGroup. Checkbox(String, CheckboxGroup, boolean) Constructs a new Checkbox with the given String label and the given state (true if it is initially checked, or false if it is not). It is specified as a member of the given CheckboxGroup. addItemListener(ItemListener) Adds the given ItemListener. CheckboxGroup getCheckboxGroup() Returns this Checkbox’s CheckboxGroup or null if it is not part of a CheckboxGroup. String getLabel() Returns the label associated with this Checkbox. boolean getState() Returns whether this Checkbox is checked. removeItemListener(ItemListener) Removes the specified ItemListener. setCheckboxGroup(CheckboxGroup) Sets this Checkbox’s CheckboxGroup. setLabel(String) Sets this Checkbox’s label. setState(boolean) Sets whether this Checkbox is checked. TABLE 6.10 C HECKBOX M ETHODS JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 199 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Checkbox cb3 = new Checkbox(“Celery”); Checkbox cb4 = new Checkbox(“Garlic”, true); cb4.setEnabled(false); Checkbox cb5 = new Checkbox(“Tomatoes”); Checkbox cb6 = new Checkbox(“Salt”, true); Checkbox cb7 = new Checkbox(“Pepper”, false); Checkbox cb8 = new Checkbox(); cb8.setLabel(“Sugar”); cb8.setState(false); cb8.setEnabled(false); //Make the Frame and add the Checkboxes to it ComponentTestFrame frame = new ComponentTestFrame(“Checkbox Test”); frame.add(cb1); frame.add(cb2); frame.add(cb3); frame.add(cb4); frame.add(cb5); frame.add(cb6); frame.add(cb7); frame.add(cb8); frame.setVisible(true); } public static void main(String args[]) { CheckboxTest cbt = new CheckboxTest(); } } 200 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r FIGURE 6.10 These Checkbox components are either checked or unchecked. More than one box can be checked at a time. Using the CheckboxGroup Class The CheckboxGroup class is used to group Checkbox objects together in such a way that only one of them can be selected at any given time. Simply specifying mul- tiple Checkboxes as belonging to one CheckboxGroup does this: CheckboxGroup group = new CheckboxGroup(); Checkbox cb1 = new Checkbox(“One”, true, group); Checkbox cb2 = new Checkbox(“Two”, false, group); Checkbox cb3 = new Checkbox(“Three”, false, group); JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 200 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. This code creates three Checkboxes that are all part of the same CheckboxGroup. Only one of them can be checked at any one time. cb1 is initially checked because of its second argument being true. Checking any of the other two will cause cb1 to become unchecked. The CheckboxGroup class defines methods used for setting and getting the selected Checkbox: Checkbox getSelectedCheckbox(), which returns the Checkbox in the group that is currently checked, and setSelected- Checkbox(Checkbox) , which checks the given Checkbox. Checkboxes in a CheckboxGroup are also sometimes called radio buttons. The CheckboxGroupTest application adds all its Checkboxes to the same Checkbox- Group . When you run it, notice that only one of them can be checked at any given time. The output is shown in Figure 6.11. Here is a listing of the source code: /* * CheckboxGroupTest * Demonstrates the CheckboxGroup Class */ import java.awt.*; public class CheckboxGroupTest { public CheckboxGroupTest() { //Make the CheckboxGroup CheckboxGroup cbg = new CheckboxGroup(); Checkbox cb1 = new Checkbox(“Red”, false, cbg); Checkbox cb2 = new Checkbox(“Green”, false, cbg); Checkbox cb3 = new Checkbox(“Blue”, false, cbg); Checkbox cb4 = new Checkbox(“Yellow”, true, cbg); cb4.setEnabled(false); Checkbox cb5 = new Checkbox(“Orange”, false, cbg); Checkbox cb6 = new Checkbox(“Purple”, false, cbg); Checkbox cb7 = new Checkbox(“Cyan”, false, cbg); Checkbox cb8 = new Checkbox(“Magenta”, false, cbg); //Make the Frame and add the Checkboxes to it ComponentTestFrame frame = new ComponentTestFrame(“CheckboxGroup Test”); frame.add(cb1); frame.add(cb2); frame.add(cb3); frame.add(cb4); frame.add(cb5); frame.add(cb6); frame.add(cb7); frame.add(cb8); frame.setVisible(true); } HINT 201 C h a p t e r 6 C r e a t i n g a G U I U s i n g t h e A b s t r a c t W i n d o w i n g T o o l k i t JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 201 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. public static void main(String args[]) { CheckboxGroupTest cbgt = new CheckboxGroupTest(); } } 202 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r FIGURE 6.11 The CheckboxGroup class groups Checkbox components together so that only one can be checked at a time. The Canvas Component A Canvas is a blank rectangular area primarily used for displaying graphics or for capturing user events. The CanvasTest application creates four Canvas objects and displays them in the frame. One important thing to note is that CanvasTest extends Canvas. It overrides its paint(Graphics) method, which is inherited from the Component class, so all other components have it too. It is responsible for ren- dering the component’s graphics and drawing them on-screen. Although this is not covered in detail until the next chapter, I included a bit of it here because the Canvas component is not very useful without displaying some kind of graphical representation. Remember your first applet way back in Chapter 1? You used the drawString(String, int, int) method there too. This program simply creates the Canvases, changes their colors, and displays them in the frame. Canvases are typically used in GUI interfaces to display an image, or some other graphic, such as a corporate logo, within a frame. The output is shown in Figure 6.12. Here is the source code: /* * CanvasTest * Demonstrates the Canvas Component */ import java.awt.*; public class CanvasTest extends Canvas { public static void main(String args[]) { //Make the Canvas CanvasTest c1 = new CanvasTest(); c1.setSize(100, 100); JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 202 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CanvasTest c2 = new CanvasTest(); c2.setSize(100, 100); c2.setBackground(Color.orange); c2.setForeground(Color.blue); CanvasTest c3 = new CanvasTest(); c3.setSize(200, 50); c3.setBackground(Color.white); c3.setForeground(Color.lightGray); CanvasTest c4 = new CanvasTest(); c4.setSize(80, 150); c4.setBackground(Color.darkGray); c4.setForeground(Color.white); //Make the Frame and add the Canvas ComponentTestFrame frame = new ComponentTestFrame(“Canvas Test”); frame.add(c1); frame.add(c2); frame.add(c3); frame.add(c4); frame.setVisible(true); } /* Override the paint() method to alter its graphics */ public void paint(Graphics g) { g.setFont(new Font(“Arial”, Font.ITALIC + Font.BOLD, 16)); g.drawString(“Canvas”, 15, 25); } } 203 C h a p t e r 6 C r e a t i n g a G U I U s i n g t h e A b s t r a c t W i n d o w i n g T o o l k i t The Menu Component Every Frame object can be associated with a MenuBar. A Frame’s MenuBar is usually at the top of the Frame, underneath the title bar. It contains a set of options, which themselves are Menus. A Menu appears when an option is selected from the MenuBar. Menus drop down from the MenuBar when they are selected and contain FIGURE 6.12 A Canvas is a component that can display graphics by overriding the paint() method. JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 203 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. MenuItems. A MenuItem is an option that exists within a Menu. Some of the more common MenuItem methods are summarized in Table 6.11. To use MenuItems, you must first create them, add them to Menus, then add the Menus to the MenuBar, and then finally associate the MenuBar with the Frame. Here’s a quick example: MenuItem myItem = new MenuItem(“Some Option”); Menu myMenu = new Menu(“Some Menu Title”); myMenu.add(myItem); MenuBar myBar = new MenuBar(); myBar.add(myMenu); frame.setMenuBar(myMenuBar); This assumes that frame is a valid Frame object. Shortcut keys are also supported. You can assign a shortcut key to a MenuItem, so that instead of clicking the menu bar and selecting the menu and finally the MenuItem, you can use a keyboard shortcut. This is set either in the MenuItem(String, MenuShortcut) constructor or the setShortcut(MenuShortcut) method. The MenuShortcut class defines which key or key combo is the shortcut. You specify this combo using KeyEvent constants. The MenuTest application sets some shortcuts just to demonstrate how it’s done. 204 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r Method Description MenuItem() Constructs a new MenuItem object. MenuItem(String) Constructs a new MenuItem object with the given label. MenuItem(String, MenuShortcut) Constructs a new MenuItem object with the given label and MenuShortcut. addActionListener(ActionListener) Adds the specified ActionListener to this MenuItem. String getLabel() Returns this MenuItem’s label. MenuShortcut getShortcut() Returns this MenuItem’s MenuShortcut. boolean isEnabled() Returns whether this MenuItem is enabled. removeActionListener(ActionListener) Removes this MenuItem’s ActionListener. setEnabled(boolean) Sets whether this MenuItem is enabled. setLabel(String) Sets this MenuItem object’s label to the specified String. setShortcut(MenuShortcut) Sets this MenuItem’s shortcut to the specified MenuShortcut. TABLE 6.11 M ENU I TEM M ETHODS JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 204 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. The MenuTest application builds two Menus for the MenuBar and sets the MenuBar for the Frame. Here is the source: /* * MenuTest * Demonstrates the MenuBar, Menu, and MenuItem classes */ import java.awt.*; import java.awt.event.KeyEvent; public class MenuTest { public MenuTest() { //create MenuBar object MenuBar menuBar = new MenuBar(); //create a Menu object Menu fileMenu = new Menu(“File”); //create MenuItem objects MenuItem fm_new = new MenuItem(“New”); fm_new.setShortcut(new MenuShortcut(KeyEvent.VK_N)); MenuItem fm_open = new MenuItem(“Open”); fm_open.setShortcut(new MenuShortcut(KeyEvent.VK_O)); MenuItem fm_save = new MenuItem(“Save”); fm_save.setShortcut(new MenuShortcut(KeyEvent.VK_S)); fm_save.setEnabled(false); MenuItem fm_saveAs = new MenuItem(“Save As ”); fm_saveAs.setShortcut(new MenuShortcut(KeyEvent.VK_A)); fm_saveAs.setEnabled(false); MenuItem fm_exit = new MenuItem(“Exit”); //add the MenuItems to the Menu with a Separator fileMenu.add(fm_new); fileMenu.add(fm_open); fileMenu.add(fm_save); fileMenu.add(fm_saveAs); //separator fileMenu.addSeparator(); fileMenu.add(fm_exit); //make another quick Menu Menu editMenu = new Menu(“Edit”); MenuItem em_options = new MenuItem(“Options”); editMenu.add(em_options); //add the Menus to the MenuBar menuBar.add(fileMenu); menuBar.add(editMenu); //create the Frame and add the MenuBar ComponentTestFrame frame = new ComponentTestFrame(“Menu Test”); 205 C h a p t e r 6 C r e a t i n g a G U I U s i n g t h e A b s t r a c t W i n d o w i n g T o o l k i t JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 205 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. frame.setMenuBar(menuBar); frame.setBackground(Color.white); frame.setVisible(true); } public static void main(String args[]) { MenuTest mt = new MenuTest(); } } It demonstrates how creating a bunch of MenuItems and dumping them into the Menus then adding the Menus to the MenuBar does this. Here is an explanation for the more complicated parts. The fm_new MenuItem adds a shortcut: fm_new.setShortcut(new MenuShortcut(KeyEvent.VK_N)); Basically, the KeyEvent.VK_N constant specifies the N key on your keyboard. You can see in the output in Figure 6.13 that this shortcut is indicated right next to the MenuItem’s label. It is Ctrl+N, although it might vary for different operating systems. Menus can also have separator lines that are used to separate different groups of MenuItems (for cosmetic sake). You do this by calling the addSeparator() method in the Menu class. Here’s an example from MenuTest.java. fileMenu.addSeparator(); This line of code added a separator in the File menu, right in between the Save As… and Exit options. Some of the MenuItems were disabled. You can see the dif- ference in their appearance. Although it is not shown here, you can nest Menus. Menu is a subclass of MenuItem, so it is a MenuItem itself and can be added to other Menus. Try it out and see for yourself! TRICK 206 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r FIGURE 6.13 The Menu class allows users to select options from a Frame’s MenuBar. JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 206 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. The PopupMenu Component The PopupMenu component is a subclass of Menu that doesn’t have to be attached to a MenuBar. It can pop up anywhere you specify it to by indicating a Component and an x and y position relative to that Component’s coordinate space. You can attach a PopupMenu to a MenuBar or another Menu, but if you do, you can’t show it at any old location that you choose because it is attached to something else. A PopupMenu is created similar to other Menus. It becomes visible by calling its show(Component, int, int) method. The specified Component’s coordinate space is used as a reference and the top-left corner of the PopupMenu is set to the loca- tion specified by the second and third arguments (x, y). The PopupMenuTest appli- cation demonstrates these concepts. The output is shown in Figure 6.14. When you run it, the PopupMenu is initially shown, if you click anywhere at all, though, it will simply disappear. This example demonstrates the basics of creating a pop- up menu. In the real world, you would cause the pop-up menu to become visible based on some event, such as right-clicking the frame. Also, you should associate actions that are triggered when the user selects a menu item. Text editors might use a pop-up menu that offers the Clipboard options (cut, copy, paste). Here is a listing of the source code for the PopupMenuTest.java example. /* * PopupMenuTest * Demonstrates the PopupMenu Component */ import java.awt.*; public class PopupMenuTest { public PopupMenuTest() { //create the PopupMenu PopupMenu popMenu = new PopupMenu(“Clipboard”); //create the MenuItems MenuItem pm_cut = new MenuItem(“Cut”); MenuItem pm_copy = new MenuItem(“Copy”); MenuItem pm_paste = new MenuItem(“Paste”); MenuItem pm_delete = new MenuItem(“Delete”); //add the MenuItems to the PopupMenu popMenu.add(pm_cut); popMenu.add(pm_copy); popMenu.add(pm_paste); popMenu.add(pm_delete); //create the Frame and make show the PopupMenu ComponentTestFrame frame = new ComponentTestFrame(“PopupMenu Test”); frame.add(popMenu); frame.setVisible(true); popMenu.show(frame, 50, 50); } 207 C h a p t e r 6 C r e a t i n g a G U I U s i n g t h e A b s t r a c t W i n d o w i n g T o o l k i t JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 207 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... two freely Here is the source code for DialogTest .java: JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 214 Java Programming for the Absolute Beginner 214 The event handling is a bit funky, but you can ignore the specifics for now, until the next chapter Simplified, the line ((Dialog)e.getSource()).setVisible(false); just means whichever Dialog you clicked the close box for should close You can see the dialog... p2.setBackground(Color.darkGray); p2.setForeground(Color.white); CheckboxGroup cbg = new CheckboxGroup(); p2.add(new Label(“Pick one:”)); p2.add(new Checkbox(“Lead Guitar”, false, cbg)); p2.add(new Checkbox(“Bass Guitar”, false, cbg)); p2.add(new Checkbox(“Drums”, false, cbg)); p2.add(new Button(“OK”)); p2.setSize(100, 500); JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 210 210 Java Programming for the Absolute Beginner TA... Modal Dialog windows must be closed before the Frame or Dialog it owns can gain user input focus Back to the MadLib Game Application Okay, back to the MadLib game application! You use your newly acquired GUI programming skills to build this game You are creating two program files for this application—MadDialog .java and MadLib .java These programs work together to form the MadLib application Creating...JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 208 Java Programming for the Absolute Beginner 208 public static void main(String args[]) { PopupMenuTest pmt = new PopupMenuTest(); } } FIGURE 6.14 A PopupMenu is similar to a Menu except it’s... code for ScrollbarTest .java follows You can see in the source code how the labels that represent the minimum and maximum values are built to be accurate The output is shown in Figure 6.16 Chapter 6 getPreferredSize() method Remember that you set the ComponentTestFrame’s layout manager to FlowLayout()? Well, that actually resizes a component based JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 212 Java Programming. .. male, female, most, least; private Choice color, time; private List prep; private TextArea text; Chapter 6 /* * MadDialog * Used by MadLib to collect user input */ JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 216 Java Programming for the Absolute Beginner 216 avPanel.add(av1); avPanel.add(av2); add(avPanel); Panel boPanel = new Panel(); boPanel.add(new Label(“Bodypart:”)); body = new TextField(10); boPanel.add(body);... owner, the specified String title, and a boolean that indicates whether this Dialog is modal TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 213 213 import java. awt.*; import java. awt.event.*; public class DialogTest implements WindowListener { public DialogTest() { //Make the Frame... the source for PanelTest .java The output is shown in Figure 6.15 /* * PanelTest * Demonstrates the Panel Component */ import java. awt.*; public class PanelTest { public PanelTest() { //Create the Panels and add components to them Panel p1 = new Panel(); p1.setBackground(Color.red); p1.add(new Label(“URL:”, Label.RIGHT)); p1.add(new TextField(25)); p1.add(new Button(“Go”)); TEAM LinG - Live, Informative,... over setting them individually because it maintains consistency.) TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 211 211 /* * ScrollbarTest * Demonstrates the Scrollbar Component */ import java. awt.*; public class ScrollbarTest extends Scrollbar { public ScrollbarTest(int orientation,... getStringArray() method is for the benefit of the MadLib class It takes all the Strings associated with the user’s input and adds them to a Vector, simply because it’s easier that way, and then converts the Vector to a String array and returns it Here is the source code: TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-06.qxd . two Menus for the MenuBar and sets the MenuBar for the Frame. Here is the source: /* * MenuTest * Demonstrates the MenuBar, Menu, and MenuItem classes */ import java. awt.*; import java. awt.event.KeyEvent; public. between the two freely. Here is the source code for DialogTest .java: /* * DialogTest * Tests the Dialog Component */ import java. awt.*; import java. awt.event.*; public class DialogTest implements. build this game. You are creating two program files for this application— MadDialog .java and MadLib .java. These programs work together to form the MadLib application. Creating the MadDialog

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

Từ khóa liên quan

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

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

Tài liệu liên quan