Java Programming for absolute beginner- P11

Chia sẻ: Cong Thanh | Ngày: | Loại File: PDF | Số trang:20

0
38
lượt xem
5
download

Java Programming for absolute beginner- P11

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Java Programming for absolute beginner- P11:Hello and welcome to Java Programming for the Absolute Beginner. You probably already have a good understanding of how to use your computer. These days it’s hard to find someone who doesn’t, given the importance of computers in today’s world. Learning to control your computer intimately is what will separate you from the pack! By reading this book, you learn how to accomplish just that through the magic of programming.

Chủ đề:
Lưu

Nội dung Text: Java Programming for absolute beginner- P11

  1. JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 158 158 toString() method in the BigTruck class overrides this method to include whether or not a trailer is attached. First you used what you learned about the Java Programming for the Absolute Beginner super keyword to call Automobile’s version of the method, and then you simply appended the trailer value. Polymorphism Polymorphism is another complicated word for a simple concept. It simply means that an instance of a subclass is also an instance of its superclass. A BigTruck instance is an Automobile too. All classes inherit from the Object class defined in the Java language, so every instance of Automobile and BigTruck is also an instance of Object. For example, if a method existed that accepted an Automobile object as a parameter: public void doSomething(Automobile auto) { … } You can pass in a BigTruck object, because it is an Automobile: BigTruck truck = new BigTruck(); doSomething(truck); Back to the BlackJack Game You’ve learned a great deal about object-oriented programming in this chapter. Now you put this knowledge to good use by creating a text-based version of a blackjack game. In this section you subclass the CardDeck class, to create Random- CardDeck, a randomized deck of cards so the game isn’t predictable. You also learn about the java.util.Vector class, which will help in creating the final game. Finally, you write the actual BlackJack application. The RandomCardDeck Class You’ve already written a class that represents a deck of cards, the CardDeck class. Now you just need to override it so that the Cards stored in the deck are random- ized. To do this, you import the java.util.Random class. In the constructor, you call the superclass’s constructor to build a regular CardDeck, and then you call the new shuffle() method to rearrange the Cards randomly. One other thing you need to do is override the reset() method so that when you reset the top card, you also shuffle the deck. Here is the source listing for RandomCardDeck.java: /* * RandomCardDeck * Simulates a shuffled deck of cards */ TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  2. JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 159 159 import java.util.Random; Chapter 5 public class RandomCardDeck extends CardDeck { public RandomCardDeck () { super(); shuffle(); } Blackjack: Object-Oriented Programming public void shuffle() { Card[] shuffled = new Card[cards.length]; Random rand = new Random(); int cIndex; boolean placed; for (int c=0; c < cards.length; c++) { do { placed = false; cIndex = rand.nextInt(cards.length); if (shuffled[cIndex] == null) { shuffled[cIndex] = cards[c]; placed = true; } } while (!placed); } cards = shuffled; top = 0; } public void reset() { super.reset(); shuffle(); } } The shuffle() method deserves some elaboration. A new Card array, shuffled, is declared locally in this method. Its purpose is to be a temporary placeholder for the deck of cards as it is being shuffled. It is initialized to the same size as the cards array instance variable. This initializes the Card objects in the shuffled array to null. The for loop loops on all the Cards in the existing cards array, one at a time. Then a random index for the shuffled array is created. If a card has not already been placed at this index, stored in cIndex (you can tell because the Card object there is null), the card is placed there; if it is already occupied by another Card, it continues to look for vacancies until it finds one. So, the cards in the cards array are copied, one by one, randomly into the shuf- fled array, and then the shuffled array is assigned to the cards instance variable, causing it to be shuffled, and then the top variable is reset to 0. The RandomCard- DeckTest program tests to make sure that the RandomCardDeck class works the way you expect it to. The output is shown in Figure 5.11. 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.
  3. JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 160 160 Java Programming for the Absolute Beginner FIGURE 5.11 The RandomCardDeck class represents a random deck of playing cards. /* * RandomCardDeckTest * Tests the RandomCardDeck class */ public class RandomCardDeckTest { public static void main(String args[]) { RandomCardDeck deck = new RandomCardDeck(); System.out.println(“Deck list:”); deck.list(); Card card = deck.deal(); System.out.println(“Dealt “ + card); System.out.println(“Shuffling...”); deck.shuffle(); System.out.println(“Deck list:”); deck.list(); } } The Vector Class The java.util package contains many useful classes, including the Random and Vector classes. The Vector class implements a growable array of objects. It acts similarly to an array except that the size automatically grows and shrinks as objects are added and removed. It is of interest here because you use the Vector class to represent the dealer’s and the player’s hand in the BlackJack game. Table 5.1 contains some useful Vector methods. Remember that because of polymor- phism, any object can be passed to the methods that accept an Object instance. The VectorVictor application demonstrates simple use of the Vector class. The source code for VectorVictor.java is as follows: TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  4. JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 161 161 TA B L E 5 . 1 V ECTOR M E T H O D S Chapter 5 Method Description void add(int index, Object element) Inserts element at the specified index, shifting the remaining indices by adding 1. boolean add(Object element) Appends element to the end; returns true. Blackjack: Object-Oriented Programming int capacity() Returns the capacity (current maximum size). void clear() Removes all elements. void copyInto(Object[] anArray) Copies the Vector’s elements into the given array. Object elementAt(int index) Returns the element at the given index. Object remove(int index) Removes and returns the object at the given index. boolean remove(Object element) Removes the first occurrence of element. void trimToSize() Sets the capacity of the Vector to its current size. /* * VectorVictor * Demonstrates the Vector class */ import java.util.Vector; public class VectorVictor { public static void main(String args[]) { //initialize a vector of capacity 5 and increment 5 Vector v = new Vector(5, 5); System.out.println(“size, capacity”); System.out.println(v.size() + “, “ + v.capacity()); v.add(new String(“Fuzzy”)); System.out.println(v.size() + “, “ + v.capacity()); v.add(new String(“Wuzzy”)); System.out.println(v.size() + “, “ + v.capacity()); v.add(new String(“was”)); System.out.println(v.size() + “, “ + v.capacity()); v.add(new String(“a”)); System.out.println(v.size() + “, “ + v.capacity()); v.add(new String(“bear”)); System.out.println(v.size() + “, “ + v.capacity()); v.add(new String(“Fuzzy”)); System.out.println(v.size() + “, “ + v.capacity()); v.add(new String(“Wuzzy”)); System.out.println(v.size() + “, “ + v.capacity()); TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  5. JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 162 162 v.add(new String(“had”)); System.out.println(v.size() + “, “ + v.capacity()); Java Programming for the Absolute Beginner v.add(new String(“no”)); System.out.println(v.size() + “, “ + v.capacity()); v.add(new String(“hair”)); System.out.println(v.size() + “, “ + v.capacity()); v.add(new String(“Fuzzy”)); System.out.println(v.size() + “, “ + v.capacity()); v.add(new String(“Wuzzy”)); System.out.println(v.size() + “, “ + v.capacity()); v.add(new String(“wasn’t”)); System.out.println(v.size() + “, “ + v.capacity()); v.add(new String(“fuzzy”)); System.out.println(v.size() + “, “ + v.capacity()); v.add(new String(“was”)); System.out.println(v.size() + “, “ + v.capacity()); v.add(new String(“he”)); System.out.println(v.size() + “, “ + v.capacity()); v.trimToSize(); System.out.println(v.size() + “, “ + v.capacity()); //copy into an array String[] str = new String[v.size()]; v.copyInto(str); for (int s=0; s < str.length; s++) { System.out.print(str[s] + “ “); } } } The constructor accepts two int arguments. The first argument is the initial capacity of the Vector and the second one is the capacity increment. The capac- ity increment is the amount by which the capacity increases any time adding an element to the Vector causes the size to be greater than its capacity. As you can see in the output shown in Figure 5.12, anytime the size of the Vector exceeds FIGURE 5.12 What’s your Vector, Victor? TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  6. JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 163 163 the capacity, it grows by a factor of 5. This program also demonstrates copying the elements of the Vector into an array. Chapter 5 The BlackJack Program Okay, here it is, the final project source code listing for BlackJack.java: /* Blackjack: Object-Oriented Programming * BlackJack * A simple BlackJack card game simulation */ import java.util.Vector; import java.io.*; public class BlackJack { protected RandomCardDeck deck; protected Vector dealerHand, playerHand; protected int dealerPoints, playerPoints; protected final static char HIT = ‘H’, STAND = ‘S’; public BlackJack() { Card card; dealerHand = new Vector(); playerHand = new Vector(); deck = new RandomCardDeck(); for (int c=0; c < deck.getNumCards(); c++) { card = deck.getCard(c); if (card.isPictureCard()) { card.setValue(10); } else if (card.getFaceValue() == Card.ACE) { card.setValue(1); } } } public static void main(String args[]) { BufferedReader reader; char input; BlackJack bj = new BlackJack(); reader = new BufferedReader(new InputStreamReader(System.in)); do { bj.play(); System.out.print(“Play Again (Y/N)? “); try { input = Character.toUpperCase(reader.readLine().charAt(0)); } catch (IOException ioe) { input = ‘?’; } } while (input == ‘Y’); } TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  7. JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 164 164 public void play() { int input; Java Programming for the Absolute Beginner dealerHand.clear(); playerHand.clear(); if (deck.getNumCardsLeft() 21) { System.out.println(“Player BUSTS!”); ((Card)dealerHand.elementAt(0)).setVisible(true); output(); System.out.println(“Player loses.”); } } while (input == HIT && playerPoints < 21); if (playerPoints
  8. JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 165 165 if (dealerPoints > 21) { System.out.println(“Dealer BUSTS!”); Chapter 5 System.out.println(“Player wins!”); } else if (dealerBlackJack()) { System.out.println(“Dealer has BlackJack.”); System.out.println(“Player loses.”); } else if (dealerPoints == playerPoints) { Blackjack: Object-Oriented Programming System.out.println(“The game is a PUSH.”); } else if (dealerPoints > playerPoints) { System.out.println(“Player loses.”); } else { System.out.println(“Player wins!”); } } } } protected void deal() { Card card; playerHand.add(deck.deal()); playerHand.add(deck.deal()); card = deck.deal(); card.setVisible(false); dealerHand.add(card); dealerHand.add(deck.deal()); updatePoints(); } protected void output() { String d = “Dealer’s Hand: “; String p = “Your Hand : “; for (int c=0; c < dealerHand.size(); c++) { d += (Card)dealerHand.elementAt(c) + “ “; } for (int c=0; c < playerHand.size(); c++) { p += (Card)playerHand.elementAt(c) + “ “; } if (d.indexOf(‘?’) == -1) { d += “ (“ + dealerPoints +”)”; } p += “ (“ + playerPoints +”)”; System.out.println(d); System.out.println(p); } protected Card hitPlayer() { return hit(playerHand); } TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  9. JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 166 166 protected Card hitDealer() { return hit(dealerHand); Java Programming for the Absolute Beginner } protected char getUserInput() throws IOException { BufferedReader reader; char input; reader = new BufferedReader(new InputStreamReader(System.in)); do { System.out.print(“(H)it or (S)tand? “); input = Character.toUpperCase(reader.readLine().charAt(0)); } while (input != HIT && input != STAND); return input; } protected boolean dealerBlackJack() { if (dealerHand.size() == 2) { if (((Card)dealerHand.elementAt(1)).getFaceValue() == Card.ACE || ((Card)dealerHand.elementAt(0)).getVisible()) { return dealerPoints == 21; } } return false; } protected boolean playerBlackJack() { if (playerHand.size() == 2) { return playerPoints == 21; } return false; } private Card hit(Vector hand) { Card card = deck.deal(); hand.add(card); updatePoints(); return card; } protected void updatePoints() { playerPoints = addUpPoints(playerHand); dealerPoints = addUpPoints(dealerHand); } private int addUpPoints(Vector hand) { int points = 0; int nAces = 0; Card[] cards = new Card[hand.size()]; hand.copyInto(cards); for (int c=0; c < cards.length; c++) { points += cards[c].getValue(); if (cards[c].getFaceValue() == Card.ACE) nAces++; } TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  10. JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 167 167 if (points 0) { points += 10; Chapter 5 } return points; } } This class defines five instance variables. deck is a RandomCardDeck object that Blackjack: Object-Oriented Programming stores the deck of cards. dealerHand and playerHand are Vector objects that rep- resent the dealer’s cards and the player’s cards, respectively. dealerPoints and playerPoints store the dealer’s points and the player’s points. There are also two class variable char constants, HIT and STAND. They are used as flags that are com- pared to user input in order to determine whether the user wants to hit or stand. The constructor initializes the game for playing. The most notable thing in the game is where it calls the isPictureCard() method defined in the Card class. You do this so that you can set the value of all picture cards to 10. Also, it references the Card.ACE constant to find the Aces and set their initial values to 1. The main() method creates a new BlackJack instance and calls the play() method in a do-while loop. It continues to call play() while the users enter Y to continue playing. Aside from the main() method, play() is the only other public method. In this implementation of the BlackJack game, it is not necessary to give everyone access to any other method. You allow instances to only call the play() method, which defines one hand of blackjack. If you decide to create a new ver- sion of the game, you can always subclass or redefine the BlackJack class itself. The play() Method: BlackJack Driver The play() method is the driver for the game. First it clears the dealer’s and player’s hands. Then it shuffles the deck if the number of remaining cards is run- ning low (15 or fewer). It deals the cards by calling the deal() method, which basically deals the cards to the dealer (one face down and one face up) and the player (both cards visible). When it prints the cards, it calls the output() method, which builds a String representation of the hands. Note that when the Vector’s elementAt() method is called, the return value must be cast to a Card object in order to get its String representation: p += (Card)playerHand.elementAt(c) + “ “; If after the cards are dealt, either the dealer or the player has blackjack, the hand is over; otherwise the player is prompted to hit or stand. The getUserInput() method prompts the users. It will accept only an H or an S and will continue to prompt the user until it gets one of those responses. This method throws an IOException, which is caught back in play(), where if it does occur, in order to TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  11. JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 168 168 end the hand gracefully, sets the user response to BlackJack.STAND, ending the player’s turn. Once the player’s turn is done, it moves on to the dealer. The dealer Java Programming for the Absolute Beginner continues to hit until the dealer’s hand is 17 or more, at which point a winner can be determined. Other BlackJack Methods There are some other methods in BlackJack that exist to make the implementa- tion of the class easier. The hitPlayer() and hitDealer() are both protected methods. This allows any subclasses to call them. It is beneficial to have one method for hitting the player and another for hitting the dealer, so you can spec- ify which hand will have a Card added to it without having to pass in a Vector representation of the hand. It is not a big deal, but would be possible to throw in any old Vector, giving the methods the capability to behave differently than they are intended to. Here, they should only be hitting the hands defined in this class. It is also true that hitting the dealer and player are similar operations, that’s why there is a private hit() method that accepts a Vector argument and adds a Card to it. Being private, it is hidden from outside implementers and sub- classes. The dealerBlackJack() and playerBlackJack() methods return a Boolean value that indicates whether the dealer or player has blackjack. For the player’s hand, this is straightforward. Does the player have two cards that add up to 21? If so then the player has blackjack. For the dealer, in this interpretation of the game, it is a bit different. The dealer can have two cards that add up to 21, but he has one card hidden. If the face-up card is an Ace, the dealer will show you right away if he has blackjack, but if he has blackjack, with the 10-card face up, he won’t show you until its his turn. The guts of the method determine whether the card is hidden and handle these situations. The updatePoints() method updates both the dealer’s and the player’s points by calling the private addUpPoints() method, which accepts a Vector argument, for both hands. The interesting things about this method are that first, it copies the Cards into a Card array from the Vector passed to it. Then it loops on this array, and adds up the points. An Ace can be either 1 or 11 points. This method calculates the points for Aces that bring the total points closest to 21 without going over. Figure 5.13 shows the output of another session of the game, where the player plays multiple times. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  12. JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 169 169 Chapter 5 Blackjack: Object-Oriented Programming FIGURE 5.13 The player pushes a couple of games of BlackJack. Summary This chapter is arguably one of the most important chapters to understand. Java is an object-oriented programming language, and every Java program you write reflects this fact. In this chapter, you learned how to define a class. You learned about instance and class variables and methods. You also learned about the access modifiers public, protected, and private. You learned many other OOP concepts that you use in the rest of the book as well. In the next chapter, you move away from the text-based programs and learn about graphical user inter- face (GUI) programming. CHALLENGES 1. Create a Holder class so that it maintains a list of objects, possibly repre- sented by Strings, which you can add to or take from by using its methods. Hint: try overriding the Vector class. 2. Create a subclass of the Holder class. Use your imagination. Consider a Refrigerator class that holds food and keeps it cold, or a Wallet that holds money, perhaps. Try overriding methods defined in the Holder class. Try cre- ating some overloaded methods as well. 3. Try adding more rules and functions to the BlackJack game. Create a sub- class of BlackJack and for added fun, give the players some money and let them bet it on the game as a way of keeping score. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  13. This page intentionally left blank TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  14. JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 171 6 C H A P T E R Creating a GUI Using the Abstract Windowing Toolkit This chapter breathes some new life into your Java pro- grams. Up to this point, all your programs, aside from the simple applet in Chapter 1, have been command-prompt based. All input and output was completed through the com- mand prompts using simple text. Java’s Abstract Windowing Toolkit (AWT) package includes classes used to build a graphical interface for interacting with the users. A Graphi- cal User Interface (GUI, pronounced “gooey”) is the official term for this type of interface. In a GUI, graphics represent such components as text fields, buttons, menus, and so on, which the users interact with to pass information back and forth to the underlying program. In this chapter, you learn how to create a GUI using Java’s AWT package, java.awt. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  15. JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 172 172 Java Programming for the Absolute Beginner The Java AWT components covered in this chapter are: • Frames • Lists • Labels • Scroll bars • Buttons • Menus • Text fields • Canvases • Text areas • Panels • Check boxes • Dialog boxes • Choices The Project: MadLib Program Are you familiar with the old pen and paper Mad-Lib games? Here is a description in case you’re not. First, you are presented with requests for certain types of words such as nouns, verbs, adjectives, adverbs, and so on. Then you read a story that uses those words to form sentences that are usually pretty funny because they don’t make much sense. They don’t make much sense because the words are used out of context. Figure 6.1 shows a typical nonsensical example. In this project, a dialog box opens first, prompting the users for some words using text fields, radio buttons, choices, a list, and a text area. Then once the users click the x to close the dialog box, another window opens and displays a story that uses the input given by the users. MadLib uses a GUI to interact with the users. Throughout the rest of this chapter, you learn all about the GUI com- ponents that make up the Java AWT. You can see the output for a typical session of the MadLib game in Figure 6.1. The java.awt Package Java’s AWT package contains all the classes that are used for creating graphical user interfaces and for creating graphics and displaying images. It contains classes used for implementing GUI components such as labels, buttons, text fields, and so on. It also contains classes that are used for handling user-initiated TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  16. JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 173 173 Chapter 6 Creating a GUI Using the Abstract Windowing Toolkit FIGURE 6.1 The users enter some words and the program generates a story in the MadLib game. events; for example, when a user clicks a button or selects an item from a list. You can gain access to any of the java.awt package classes by importing them: import java.awt.*; This line imports (references, technically) any of the java.awt package classes used in your Java program, and no others. Basically, it just signifies where the classes can be found—in the java.awt package. Consult the API documentation for this package after you’ve learned the basics in this chapter for more detailed information. Components Components are the individual elements that collectively make up a graphical user interface. The Component class is the superclass for all the AWT components such as labels, buttons, text fields, and so on. Because all these components sub- class the Component class, they all have a common set of methods. These methods are summarized in Table 6.1. Keep in mind throughout the rest of this chapter, as well in Chapters 7 and 8, that these methods are common for all java.awt components. They are used extensively throughout the rest of this book. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  17. JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 174 174 HIN T All the components defined in the java.awt package are called heavyweight components because they each have a native peer associated with them. This Java Programming for the Absolute Beginner means that they are rendered using the underlying operating system’s native API behind the scenes. Java is still platform-independent because the JRE makes references to the API associated with the operating system it is installed over without requiring any difference in Java source code or recompilation. You can create lightweight components that are not associated with a native peer by subclassing the Component class directly. Java also includes a package, called “Swing” (specifically, javax.swing) that defines lightweight components ready for you to use. TA B L E 6 . 1 S O M E C OMPONENT C L A S S M E T H O D S Method Description getBackground() Returns the background color for the Component. getBounds() Returns the bounds (x and y coordinates and width and height) of this Component as a Rectangle object. getFont() Returns the Font associated with the Component. getForeground() Returns a Color object that represents this Component’s foreground color. getHeight() Returns an int that represents this Component’s height in pixels. getPreferredSize() Returns a Dimension object that represents this object’s optimal size. getSize() Returns a Dimension object that represents this object’s current size. getWidth() Returns an int that represents this Component’s width in pixels. getX() Returns an int that represents this Component’s current position in pixels from the left side of the screen. getY() Returns an int that represents this Component’s current position in pixels below the top of the screen. boolean isEnabled() Returns a boolean that indicates whether this Component is enabled. boolean isFocusTraversable() Returns a boolean that indicates whether this Component can be traversed using the Tab or Shift+Tab key operations. boolean isLightWeight() Returns whether this Component is lightweight. A Component is lightweight if it is not associated with a native peer. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  18. JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 175 175 TA B L E 6 . 1 CONTINUED Chapter 6 Method Description paint(Graphics) This method takes care of rendering the graphics that represent this Component’s appearance. repaint() This method is called to repaint this Component’s graphics after they are updated or moved. Creating a GUI Using the Abstract Windowing Toolkit setBackground(Color) Sets this Component’s background color to the given Color object. setBounds(Rectangle) Sets this Component’s bounds (x and y coordinates and width and height) to the given Rectangle object’s values. setEnabled(boolean) Sets whether this Component is enabled. Users can interact with it only if it’s enabled. setFont(Font) Sets this Component’s font to the specified Font object’s values. setLocation(int, int) Sets this Component’s location to the specified (int, int) coordinate. setSize(int, int) Sets this Component’s size to the specified width and height. setSize(Dimension) Sets this Component’s size to the specified Dimension object’s width and height. setVisible(boolean) Shows this Component if the given parameter is true, or hides it if it is false. Figure 6.2 shows the graphical representation of some of Java’s AWT components, which are described here: • Labels are used mainly for labeling other components or displaying a mes- sage for the user’s benefit. • The user interacts with Buttons to initiate some action. • You use a TextField to accept some text input from the users. • A Scrollbar defines a range of numerical values for the users to choose from. • A Checkbox is either checked or unchecked and its associated label is used for describing what the state of the Checkbox signifies. • You use the Canvas component mainly to display graphics in a confined area. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  19. JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 176 176 • The Choice component allows the users to choose one item out of a selec- tion of items. Java Programming for the Absolute Beginner • The List component is similar to the Choice component, except it allows the users in some instances to choose more than one item from a list of items. It also allows the users to view multiple items at one time. • The user interacts with the TextArea component to enter multiple lines of text, or you can use it to display longer messages to the users. • The Frame component is also a Container, so it can hold other compo- nents. The Frame class is a top-level window including a border and a title bar. You work with these components as well as others not shown here throughout this chapter. Button Scroll bar Label Check box Text field Check box group Canvas List FIGURE 6.2 The myriad Java Frame GUI components you can use in your programs. Choice Text area IN THE REAL WORLD In the real world GUIs are everywhere. You use them when interfacing with your operating system as well as when buying stuff on the Internet from e-commerce sites. An overlying GUI environment also makes it much easier to interface with a database via entries or queries. When GUIs are developed in Java, frequently developers will create their own packages and define their own unique look and feel. They will make reusable and extendable code that they can continue to build on. That is one of the benefits of an object-oriented GUI programming environment. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  20. JavaProgAbsBeg-06.qxd 2/25/03 8:52 AM Page 177 177 Events Chapter 6 Java’s AWT events are defined within the java.awt.event package. Each compo- nent has associated events, themselves defined as Java classes, that users trigger by interacting with the components. You handle these events through interface classes known as AWT event listener interfaces. You explore this in more detail in Chapter 7, “Advanced GUI: Layout Managers and Event Handling,” but you are exposed to it a bit in this chapter too. I had to at least explain how to handle a Creating a GUI Using the Abstract Windowing Toolkit WindowEvent so that you don’t have to write a bunch of GUI programs that won’t exit when you try to close the window. Basically, when the users interact with a GUI component, that component trig- gers an event. Any classes that “listen” to these events typically define a set of statements that handle the event. You make a class “listen” to these events by implementing an interface. An interface is an abstract class that predefines a set of methods. It is abstract because the methods themselves have no statements asso- ciated with them. The methods are simply predefined and must be overridden by a class that implements the interface. Put differently, say there is an event that is triggered when the user attempts to close the window by clicking the little close button (an x) in the upper-right cor- ner. There is an interface called WindowListener that declares a certain method to handle this, windowClosing(WindowEvent). If you want to create a class that lis- tens to this event, you implement the WindowListener interface in your class. When you do this, you must define the windowClosing(WindowEvent) method within your class. Then when the user clicks the button, the method you defined in your class will be called to handle the event. Don’t worry about it too much if you don’t have a full grasp of this concept yet. You deal with event handling only a very little in this chapter and don’t fully explore it until Chapter 7. Graphics The AWT also supports graphics programming. The Graphics class, defined in the java.awt package, has methods for drawing shapes, text, and images to the screen. It is responsible for rendering the actual graphics that make up all the AWT’s GUI components. It draws the lines that make a button look raised when it is not clicked and pressed when it is clicked. You learn a bit about this aspect of Java’s AWT in this chapter, and then learn even more advanced concepts in Chapter 7. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Đồng bộ tài khoản