intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

Java Programming for absolute beginner- P24

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

44
lượt xem
5
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Java Programming for absolute beginner- P24: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- P24

  1. JavaProgAbsBeg-11.qxd 2/25/03 8:57 AM Page 418 418 character at a time using the reader.read() method. If the end of the file (EOF) is reached, this method returns –1. So the while loop checks for this as its con- Java Programming for the Absolute Beginner dition. Although each character read in is not –1, write that character to the writer buffer anyway. Invoking the writer.close() causes the buffer to be cleared, written to the file, and closed. Figure 11.6 shows one run of the FileCopy application. FIGURE 11.6 The FileCopy application copied the file1.txt file and saved the copy as copy.txt. P Don’t forget to call the close() method on the BufferedWriter. If you don’t you TRA won’t get any actual output. There is also a method called flush() which flush- es the buffer and writes it out to the file, but calling close() actually flushes the buffer before closing anyway. Keeping Score The ScoreInfoPanel class keeps score basically by keeping track of three integers: scoreValue keeps track of the current score, hiValue keeps track of the high score, and nLinesValue keeps track of the number of lines cleared. The ScoreInfoPanel class also provides methods for modifying these values such as setScore(int), setHiScore(int), and setLines(int) for setting these values to the given int value. It also provides addToScore(int) and addToLines(int) TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  2. JavaProgAbsBeg-11.qxd 2/25/03 8:57 AM Page 419 419 methods for adding the given int value to these values. Here is the source code for ScoreInfoPanel.java: Chapter 11 /* * ScoreInfoPanel * A Panel that shows the scoring info for a BlockGame * and shows the next block. */ import java.awt.*; Custom Event Handling and File I/O import java.io.*; import java.text.NumberFormat; public class ScoreInfoPanel extends Panel { protected Label scoreLabel = new Label("Score: "), linesLabel = new Label("Lines: "), score = new Label(), hiLabel = new Label(), lines = new Label(), nextLabel = new Label("Next Block", Label.CENTER); protected int scoreValue = 0, hiValue = 0, nLinesValue = 0; protected BlockGrid nextBlockDisplay = new BlockGrid(6, 6, 10); public static int BLOCK = 1, ROW1 = 100, ROW2 = 300, ROW3 = 600, ROW4 = 1000, ROW4BONUS = 10000; protected Label[] points = { new Label("Block = " + BLOCK + " points"), new Label("1 Row = " + ROW1 + " points"), new Label("2 Rows = " + ROW2 + " points"), new Label("3 Rows = " + ROW3 + " points"), new Label("4 Rows = " + ROW4 + " points"), new Label("BONUS = " + ROW4BONUS + " points") }; NumberFormat nf = NumberFormat.getInstance(); Block block = null; public ScoreInfoPanel() { super(); nf.setMinimumIntegerDigits(8); //pack in zeros nf.setGroupingUsed(false); //no separators e.g. commas hiLabel.setForeground(Color.blue); readHiScore(); nextBlockDisplay.setBackground(Color.black); nextLabel.setForeground(Color.blue); scoreLabel.setForeground(Color.blue); linesLabel.setForeground(Color.blue); setScore(0); score.setAlignment(Label.CENTER); score.setForeground(Color.green); score.setBackground(Color.black); score.setFont(new Font("Courier New", Font.BOLD, 12)); setLines(0); TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  3. JavaProgAbsBeg-11.qxd 2/25/03 8:57 AM Page 420 420 lines.setAlignment(Label.CENTER); lines.setForeground(Color.red); Java Programming for the Absolute Beginner lines.setBackground(Color.black); lines.setFont(new Font("Courier New", Font.BOLD, 12)); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); setLayout(gridbag); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.anchor = GridBagConstraints.CENTER; addComp(hiLabel, gridbag, gbc); addComp(nextBlockDisplay, gridbag, gbc); addComp(nextLabel, gridbag, gbc); gbc.anchor = GridBagConstraints.WEST; for (int p=0; p < points.length; p++) { addComp(points[p], gridbag, gbc); } addComp(scoreLabel, gridbag, gbc); gbc.anchor = GridBagConstraints.CENTER; addComp(score, gridbag, gbc); gbc.anchor = GridBagConstraints.WEST; addComp(linesLabel, gridbag, gbc); gbc.anchor = GridBagConstraints.CENTER; addComp(lines, gridbag, gbc); } protected void addComp(Component comp, GridBagLayout g, GridBagConstraints c) { g.setConstraints(comp, c); add(comp); } protected void readHiScore() { try { BufferedReader r = new BufferedReader(new FileReader("hi.dat")); setHiScore(Integer.parseInt(r.readLine())); r.close(); } catch (Exception e) { setHiScore(0); } } public void saveHiScore() { try { BufferedWriter w = new BufferedWriter(new FileWriter("hi.dat")); w.write(String.valueOf(hiValue)); w.close(); } catch (Exception e) {} } protected void setHiScore(int h) { hiValue = h; hiLabel.setText("High: " + nf.format(h)); } TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  4. JavaProgAbsBeg-11.qxd 2/25/03 8:57 AM Page 421 421 public void setScore(int s) { scoreValue = s; Chapter 11 score.setText(nf.format(s)); if (s > hiValue) setHiScore(s); } public void addToScore(int addValue) { scoreValue += addValue; setScore(scoreValue); } Custom Event Handling and File I/O public void setLines(int l) { nLinesValue = l; lines.setText(nf.format(l)); } public void addToLines(int addValue) { nLinesValue += addValue; setLines(nLinesValue); } public void showBlock(Block b) { if (block != null) nextBlockDisplay.removeBlock(); block = b; nextBlockDisplay.setBlock(block); nextBlockDisplay.setBlockPos(new Point(1, 1)); nextBlockDisplay.addBlock(); nextBlockDisplay.repaint(); } public Insets getInsets() { return new Insets(5, 5, 5, 5); } } The ScoreInfoPanel uses labels to display its information, defined as follows: • scoreLabel is the label for the current score • score is the label for the actual numerical score • linesLabel labels the number of lines • lines is the label that displays the number of lines • highLabel labels and displays the high score on one line • nextLabel labels the box that shows the next block nextBlockDisplay is a BlockGrid instance that displays the next block. The show- Block(Block) method can be called, and the given Block will be displayed in the TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  5. JavaProgAbsBeg-11.qxd 2/25/03 8:57 AM Page 422 422 nextBlockDisplay. The ScoreInfoPanel also provides some static constants that represent score values: Java Programming for the Absolute Beginner BLOCK The score value for landing a block. ROW1 The score value for clearing one line with a single block. ROW2 The score value for clearing two lines with a single block. ROW3 The score value for clearing three lines with a single block. ROW4 The score value for clearing four lines with a single block. BONUS The score value for clearing four lines with a single block multi- ple times. It reads and writes the high score using a file named hi.dat. These are the meth- ods that do this: protected void readHiScore() { try { BufferedReader r = new BufferedReader(new FileReader("hi.dat")); setHiScore(Integer.parseInt(r.readLine())); r.close(); } catch (Exception e) { setHiScore(0); } } public void saveHiScore() { try { BufferedWriter w = new BufferedWriter(new FileWriter("hi.dat")); w.write(String.valueOf(hiValue)); w.close(); } catch (Exception e) {} } It works similarly to the FileCopy application, except the BufferedReader reads a whole line, which you actually did way back in Chapter 2, when you used a BufferedReader to read command-line input. It parses the string read in to an integer value by calling Integer.parseInt(r.readLine()). The readHiScore() method is not public because there is no reason for any other class to tell this class to read in the high score because it does it automatically in the constructor and keeps it up to date. The saveHiScore() method, on the other hand, is public because you want to wait until the game is over before you save the score. You’ll rely on the application pro- gram to tell you when that is. The BufferedWriter writes a whole string that rep- resents the high score by calling w.write(String.valueOf(hiValue)). Everything else is pretty much straight-forward, such as laying out these components. However, the use of the NumberFormat class needs some explanation. NumberFor- mat is part of the java.text package. It helps you format numbers. I created a TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  6. JavaProgAbsBeg-11.qxd 2/25/03 8:57 AM Page 423 423 new instance of a NumberFormat by calling NumberFormat.getInstance(). Number- Format is an abstract class, so it can’t have a direct instance. getInstance() Chapter 11 returns the default number format. There are other methods for getting other types of instances such as getCurrencyInstace() and getPercentInstance(). nf is the NumberFormat. Calling nf.setMinimumIntegerDigits(8) does exactly what you’d expect it to do based on the name of the method. It expresses integers using a minimum of eight digits. For example, 27 is expressed as 00000027. nf.setGroupingUsed(false) makes sure that no commas separate the pieces of Custom Event Handling and File I/O the number (so 1000 doesn’t use a comma like 1,000). P Running Block Game from the CD will not allow you to maintain a high score. TRA You can’t write a file onto the CD, so the high score won’t get saved. The excep- tion handling will cause this flaw to just be ignored. To save your high scores, either write your own copy, which you should be doing for learning purposes anyway, or copy the games files to your hard drive and run it from there. Creating the Block Game Application The Block Game application puts the PlayArea and ScoreInfoPanel classes together, along with a Play/Reset button so you can start a new game. The mem- bers it declares are as follows: lastNLines Holds the number of lines (rows) that were cleared the last time lines where cleared. playarea The PlayArea instance. infoPanel The ScoreInfoPanel instance. resetButton The button used for playing and resetting the game. block The current block that will be introduced to the PlayArea. nextBlock The block that will be introduced to the PlayArea after block lands. I, L, O, R, S, T, and Z Constants that represent the seven block shapes. I used the letter that looks most like the shape of the block. The createBlock() method pumps out one of the seven blocks. It generates a ran- dom number and then uses a switch statement to generate the block based on that random number and then returns that block. The initialize() method sets score values to zero and creates a new block for nextBlock. The intro- duceNextBlock() method sets block to nextBlock, creates a new block for TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  7. JavaProgAbsBeg-11.qxd 2/25/03 8:57 AM Page 424 424 nextBlock, shows nextBlock in infoPanel, and calls playarea.introduce- Block(block) to make the block start falling into the PlayArea. The resetButton Java Programming for the Absolute Beginner has an ActionListener that calls the playGame() method. This method calls ini- tialize(), playarea.clear() (for clearing the PlayArea when the game is reset), playarea.requestFocus() (so the PlayArea will immediately accept keyboard commands), and introduceNextBlock() to get things rolling. It adds an anonymous inner class to listen for PlayAreaEvents to the playarea instance. It checks for block landings. It adds the point values specified by the ScoreInfoPanel constants based on how many rows are cleared. After it adds the score it checks whether the block landed out of area by invoking the isOutO- fArea() method of the PlayAreaEvent class. If it isn’t out of area, it introduces the next block into the PlayArea, if it is, the game is over and it calls infoPanel.saveHiScore() to write the high score back to the file. Here is the full source code listing for BlockGame.java: /* * Block Game * The actual Application Frame for the Block Game. */ import java.awt.*; import java.awt.event.*; public class BlockGame extends GUIFrame { protected int lastNLines; protected PlayArea playarea; protected ScoreInfoPanel infoPanel; protected Button resetButton; protected Block block, nextBlock; protected final static int I = 0, L = 1, O = 2, R = 3, S = 4, T = 5, Z = 6; public BlockGame() { super("Block Game"); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); setBackground(SystemColor.control); playarea = new PlayArea(10, 20, 20); setLayout(gridbag); playarea.setBackground(Color.black); constraints.gridheight = GridBagConstraints.REMAINDER; gridbag.setConstraints(playarea, constraints); add(playarea); TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  8. JavaProgAbsBeg-11.qxd 2/25/03 8:57 AM Page 425 425 infoPanel = new ScoreInfoPanel(); constraints.anchor = GridBagConstraints.NORTH; Chapter 11 constraints.gridheight = 1; constraints.gridwidth = GridBagConstraints.REMAINDER; gridbag.setConstraints(infoPanel, constraints); add(infoPanel); resetButton = new Button("Play/Reset"); resetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { playGame(); Custom Event Handling and File I/O } }); constraints.gridwidth = constraints.gridheight = 1; gridbag.setConstraints(resetButton, constraints); add(resetButton); playarea.addPlayAreaListener(new PlayAreaListener() { public void blockLanded(PlayAreaEvent pae) { infoPanel.addToScore(ScoreInfoPanel.BLOCK); infoPanel.addToLines(pae.getRows()); switch (pae.getRows()) { case 1: infoPanel.addToScore(ScoreInfoPanel.ROW1); break; case 2: infoPanel.addToScore(ScoreInfoPanel.ROW2); break; case 3: infoPanel.addToScore(ScoreInfoPanel.ROW3); break; case 4: infoPanel.addToScore(ScoreInfoPanel.ROW4); if (lastNLines == 4) infoPanel.addToScore(ScoreInfoPanel.ROW4BONUS); break; } lastNLines = pae.getRows() > 0 ? pae.getRows() : lastNLines; if (!pae.isOutOfArea()) introduceNextBlock(); else infoPanel.saveHiScore(); } }); initialize(); pack(); setVisible(true); } public static void main(String args[]) { new BlockGame(); } TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  9. JavaProgAbsBeg-11.qxd 2/25/03 8:57 AM Page 426 426 protected void initialize() { lastNLines = 0; Java Programming for the Absolute Beginner infoPanel.setScore(0); infoPanel.setLines(0); block = createBlock(); nextBlock = createBlock(); } public void playGame() { initialize(); playarea.clear(); playarea.requestFocus(); introduceNextBlock(); } public void introduceNextBlock() { block = nextBlock; nextBlock = createBlock(); infoPanel.showBlock(nextBlock); playarea.introduceBlock(block); } //randomly returns one of the seven blocks protected Block createBlock() { Point[] squareCoords = new Point[4]; int randB = (int) Math.floor(Math.random() * 7); int s; Color c; switch (randB) { case I: squareCoords[0] = new Point(2, 0); squareCoords[1] = new Point(2, 1); squareCoords[2] = new Point(2, 2); squareCoords[3] = new Point(2, 3); s = 4; c = Color.white; break; case L: squareCoords[0] = new Point(1, 0); squareCoords[1] = new Point(1, 1); squareCoords[2] = new Point(1, 2); squareCoords[3] = new Point(2, 2); s = 3; c = Color.blue; break; case O: squareCoords[0] = new Point(0, 0); squareCoords[1] = new Point(0, 1); squareCoords[2] = new Point(1, 0); squareCoords[3] = new Point(1, 1); s = 2; c = Color.cyan; break; TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  10. JavaProgAbsBeg-11.qxd 2/25/03 8:57 AM Page 427 427 case R: squareCoords[0] = new Point(1, 0); Chapter 11 squareCoords[1] = new Point(2, 0); squareCoords[2] = new Point(1, 1); squareCoords[3] = new Point(1, 2); s = 3; c = Color.red; break; case S: squareCoords[0] = new Point(1, 1); Custom Event Handling and File I/O squareCoords[1] = new Point(1, 2); squareCoords[2] = new Point(2, 0); squareCoords[3] = new Point(2, 1); s = 3; c = Color.yellow; break; case T: squareCoords[0] = new Point(0, 1); squareCoords[1] = new Point(1, 1); squareCoords[2] = new Point(1, 2); squareCoords[3] = new Point(2, 1); s = 3; c = Color.green; break; case Z: squareCoords[0] = new Point(1, 0); squareCoords[1] = new Point(1, 1); squareCoords[2] = new Point(2, 1); squareCoords[3] = new Point(2, 2); s = 3; c = Color.magenta; break; default : squareCoords = new Point[1]; squareCoords[0] = new Point(0, 0); s = Block.MIN_SIZE; c = Color.orange; } return new Block(s, squareCoords, c); } } Summary In this chapter, you wrote a larger scale project than in any of the preceding chapters. You learned how to create custom event-handling models. You learned about inner classes, including anonymous inner classes. You also learned some file I/O. In building the Block Game application and the classes associated with it, you used many of the concepts you learned in previous chapters. In the next TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  11. JavaProgAbsBeg-11.qxd 2/25/03 8:57 AM Page 428 428 chapter, you will learn how to create custom lightweight components, how to cre- ate your own custom packages, and also how to take advantage of the javadoc Java Programming for the Absolute Beginner utility included with the Java SDK. You will apply this knowledge to building another big project, the MinePatrol game. CHALLENGES 1. Create a program that reads a file and writes a new file that is completely backwards. 2. Create some new block shapes in the Block Game to shake things up and give your game a twist of your own. 3. Rewrite the ImageTest application from Chapter 9, except this time, extend GUIFrame and override the paint(Graphics) method by making the Canvas an anonymous inner class. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  12. JavaProgAbsBeg-12.qxd 2/25/03 8:58 AM Page 429 12 C H A P T E R Creating Your Own Components and Packages Up until this point, you’ve been either using classes from prede- fined packages included in the Java 1.3 SDK, or creating your own classes. In this chapter, you will build a package. You learn what lightweight components are and how to create them and build a package that includes three classes. It is a rather small package, but there’s a lot of code involved. The source files are rather large because of how heavily commented they are. You’re going to learn how to comment your code in such a way that you can run the javadoc utility to generate documentation for your packages. The main goals of this chapter include the following concepts: • Declare packages • Create lightweight components • Create and extend abstract classes • Use javadoc comments and run the javadoc tool • Create the MinePatrol game by importing the custom packages TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  13. JavaProgAbsBeg-12.qxd 2/25/03 8:58 AM Page 430 430 Java Programming for the Absolute Beginner The Project: MinePatrol This chapter’s project is a game that is similar to Minesweeper, a game you might be familiar with. The game board opens up and presents you with a grid of but- tons. The contents underneath the buttons are unknown until you left-click one of them. If there’s a mine hidden under one of them, you will explode and die if you click it. If there isn’t a mine directly in that cell, but there is one in close proximity, such as at least one of the surrounding eight cells, you will get an intensity reading that shows you how many mines surround that cell. If there aren’t any mines in close proximity, you can take more accurate readings and some of the surrounding cells will reveal themselves and show their inten- sity readings. In fact, all cells surrounding the clicked cell that are also empty will be revealed. None of the cells that contain mines will be revealed. Only cells that directly border an empty cell within a clear path of the cell you clicked are revealed. The object is to use the intensity readings as clues to determine where the mines are. You can flag a cell, if you think there is a mine there, by right-clicking the cell. You can’t click a cell with the left mouse button once its flagged. This prevents messy accidents. You can unflag a cell by right-clicking the cell again. You win the game by flagging all the mines and clearing the rest. The game also ends if you blow up. In either case, the entire board is revealed to you so you can see where you went wrong. Figure 12.1 shows this game in action. FIGURE 12.1 Here is the MinePatrol game. Let’s see… is there a mine here? I don’t think… KABOOM. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  14. JavaProgAbsBeg-12.qxd 2/25/03 8:58 AM Page 431 431 Creating Lightweight Components Chapter 12 AWT components are called heavyweight components because they have a native peer associated with them. This means that in order for your operating system to make use of the components, system-dependent calls are made (in the back- ground, because Java is a system-independent language) to native API. A native API (Application Programming Interface) is a term that refers to the operating system’s resident interface. Each component has its own representation depending on Creating Your Own Components and Packages what operating system you’re using. Each component is rendered in its own opaque window, which can be memory intensive. Lightweight components do not have a native peer. They represent themselves functionally and graphically. Basi- cally, you create a lightweight component by overriding the Component class. That’s it; that’s all it takes. The Swing Package No, not schwing, Garth, Swing! Take your Ritalin. The Swing package (javax.swing) provides a set of lightweight components. Swing is included with the standard edition of the Java 2 platform. Its components are all Java code and don’t have native peers. They work the same on all platforms. Although Swing is not fully covered by this book, you already have a head start. The concepts of the Swing components are similar to the concepts in the AWT package. Take the following code for instance: /* * SwingTest * Demonstrates, very basically, how to use swing */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SwingTest extends JFrame { public SwingTest() { JLabel label = new JLabel("JLabel"); JTextField tfield = new JTextField("JTextField", 15); JButton button = new JButton("JButton"); getContentPane().setLayout(new FlowLayout()); getContentPane().add(label); getContentPane().add(tfield); getContentPane().add(button); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  15. JavaProgAbsBeg-12.qxd 2/25/03 8:58 AM Page 432 432 }); pack(); Java Programming for the Absolute Beginner setVisible(true); } public static void main(String args[]) { new SwingTest(); } } You should pretty much be able to tell what is going on here just by reading the code because it is so similar to how the AWT works. The JFrame class inherits from Frame and exists to offer support for the Swing component architecture. The SwingTest class subclasses the JFrame class and adds a JLabel, a JTextField, and a JButton to itself. These three components are similar to the Label, TextField, and Button components found in the AWT, except for the fact that they are lightweight. Their appearance is different as well, as you can see in Fig- ure 12.2. JFrames, unlike their Frame ancestors, have a method that allows for some window closing handling. I passed WindowConstants.DISPOSE_ON_CLOSE to the setDefaultCloseOperation(int) method. This causes the window to be dis- posed when you close the window. However, you still need to use a WindowLis- tener if you want to exit the program when the window is closed. FIGURE 12.2 Here are a few of Swing’s lightweight components. Creating Your Own Lightweight Components There are four main steps to follow to create a useful lightweight component. 1. Extend the Component class. 2. Override paint(Graphics). 3. Call enableEvents(int). 4. Register appropriate listeners. Extending the Component class is easy, just do it like this: public class myLightWeight extends Component { … } Overriding the paint(Graphics) method is also simple enough; you’ve already done this countless times to modify the graphics of AWT components. The enableEvents(int) method enables the type of event specified by its given para- meter. These parameters are specified as static constants in the AWTEvent class TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  16. JavaProgAbsBeg-12.qxd 2/25/03 8:58 AM Page 433 433 and some of them are listed in Table 12.1. If you need to review these event types, refer to Chapter 7, “Advanced GUI: Layout Managers and Event Handling.” Chapter 12 These event types are enabled automatically when the appropriate listener is added, but the enableEvents(int) method should be called by subclasses of Com- ponent that want specific event types delivered to processEvent(AWTEvent) regardless of whether there is a registered listener. A lightweight button would want to do this, for example, to process mouse events so that its appearance Creating Your Own Components and Packages changes somewhat when it is clicked. You don’t need any registered listeners to do that; just call enableEvents(AWTEvent.MOUSE_EVENT_MASK) and handle the event in the processMouseEvent(MouseEvent) class. The generic processEvent (AWTEvent) calls whatever process method is appropriate to handle whatever the event type is. You will do this when you create the JPRButton3D lightweight component. To register listeners, you can make use of the AWTEventMulticaster class, which implements thread-safe dispatching of AWT events. Here is an example of how to register ActionListeners with your component. public class myLightWeight extends Component { ActionListener actionListener; … public void addActionListener(ActionListener listener) { actionListener = AWTEventMulticaster.add(actionListener, listener); } … } TA B L E 1 2 . 1 AWTE VENT E V E N T M A S K C O N S T A N T S Event Mask Description ACTION_EVENT_MASK Selects action events. ADJUSTMENT_EVENT_MASK Selects adjustment events. FOCUS_EVENT_MASK Selects focus events. ITEM_EVENT_MASK Selects item events. KEY_EVENT_MASK Selects key events. MOUSE_EVENT_MASK Selects mouse events. MOUSE_MOTION_EVENT_MASK Selects mouse motion events. TEXT_EVENT_MASK Selects text events. WINDOW_EVENT_MASK Selects window events. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  17. JavaProgAbsBeg-12.qxd 2/25/03 8:58 AM Page 434 434 You declare an ActionListener—here it’s named actionListener—and then pro- vide the addActionListener(ActionListener) method. Inside of that method, Java Programming for the Absolute Beginner you register the given listener with actionListener by calling AWTEventMulti- caster.add(actionListener, listener), which adds the given ActionListener argument to your actionListener and returns the result, which you store right back into actionListener. The AWTEventMulticaster class itself implements ActionListener (as well as the other types of listener interfaces) and returns an instance of itself when you call the add() methods. Its actionPerformed(Action- Event) method invokes the actionPerformed(ActionEvent) method of all the ActionListeners that were registered in this way. Preparing to Create the jpr.lightweight Package The jpr.lightweight package has three classes, described as follows: • The JPRComponent3D class represents a lightweight component. It has bor- ders that can be drawn to make the JPRComponent3D appear to be raised above its container, sunk into the surface of its container, or flat (not raised or sunk). It is an abstract class. • The JPRRectComponent3D class extends the JPRComponent3D class and defines its rectangular shape and therefore overrides the paint(Graphics) method to represent the component as a rectangular 3D shape. It is also an abstract class. • The JPRButton3D class extends the JPRRectComponent3D class and encapsu- lates a rectangular button that changes its appearance based on its state— whether it is being clicked or whether it is enabled. It is not an abstract class. Ultimately, you will use the JPRButton3D class to represent the but- tons of the MinePatrol game. Before you create this package, you need to know a few things, such as how do you declare a package? What is an abstract class? How do you use the javadoc utility to generate documentation for packages? Who had Frankie Pentangeli killed? Who gave the order? All, well most, of these questions are answered in the next few sections. Declaring Packages When you create a Java source file, it consists of three main sections: the pack- age declarations, the import statements, and the class definitions. The syntax for declaring a package is very straight-forward: package jpr.lightweight; TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  18. JavaProgAbsBeg-12.qxd 2/25/03 8:58 AM Page 435 435 The package keyword is followed by the package name. That’s it. There is more to learn about package names, however. Package names imply directory structures, Chapter 12 so the previous class file better be in a directory called jpr and then in a subdi- rectory called lightweight or you won’t be able to import the class later. P Keep in mind, your CLASSPATH variable was discussed in Chapter 1, “Getting TRA Started.” In order for you to make your packages accessible, you either have to make the package directory structure relative to the current directory or you Creating Your Own Components and Packages need to add the path of your package’s parent directory to your CLASSPATH vari- able. In this case, a parent directory has access to the package if there is a directory named jpr in it and jpr has a subdirectory named lightweight in it that contains the class files for the classes that belong to the package. Here is an example: CLASSPATH=.;C:\PACKAGES In this instance, the jpr and lightweight subdirectory structure should be in the PACKAGES folder. Not having the CLASSPATH set also causes problems when compiling one source file from the package. To get around this, if you don’t want to mess with your CLASSPATH variable, get yourself into the lightweight folder where the jpr.lightweight package source files will be and just compile them all at once like this: javac *.java Abstract Classes Abstract classes are shells of classes that defer implementation to subclasses. For instance, let’s say you have an abstract class, Automobile. You decide that all sub- classes of Automobile need a drive() method. Each subclass of automobile drives differently; a moped doesn’t drive anything like an 18-wheeler. The Automobile class has the abstract idea that all its subclasses need to override this method in order for it to make sense. The Automobile class itself has no use for it. Abstract classes cannot be instantiated, anyway. Subclasses must be defined and sub- classes of Automobile can be considered Automobiles. You’ve used abstract classes before when you used event listener interfaces. All interfaces are implic- itly abstract. Here’s what the Automobile class might look like: public abstract class Automobile { public boolean driving; public abstract void drive(); public boolean isDriving() { return driving; } } TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  19. JavaProgAbsBeg-12.qxd 2/25/03 8:58 AM Page 436 436 Notice that the drive() method is declared abstract. It has no body, and as you saw in the previous chapter, that’s how you create an abstract method. Any non- Java Programming for the Absolute Beginner abstract subclass of Automobile must provide the body for this method. Also notice that there is a non-abstract method here too: isDriving(). I put that there to show you that an abstract class can provide some actual implementation of its methods. Something as wide a concept as “is this Automobile driving?” should really be able to apply to most, if not all, subclasses of Automobile. The javadoc Utility The javadoc utility generates HTML documentation for your package classes. You can run the javadoc utility on individual class files or entire packages. You have to comment your code in a special way for this to work. Here is an example of a javadoc comment, also known as a documentation comment. /** * This is a javadoc comment */ A javadoc comment starts off like a regular multi-line comment with a forward slash and an asterisk, but the second asterisk flags this comment as a javadoc comment. The other asterisks that precede each line are not required and are ignored to the extent that they will not be included directly into the documen- tation, but they do have meaning. White space that follows the asterisk is included in the documentation, so if you are formatting your comments in your source files and you want the formatting to translate into the documentation, keep the asterisks in. Because the documentation is written in HTML, HTML tags can be used within the javadoc comments: /** * This is a javadoc comment */ The and tags surround text that should be bolded in HTML coding. javadoc also provides its own tags, which are described in Table 12.2. Note also that the first sentence of each comment should be a summary com- ment; that is, it should explain, in short, what the rest of the following com- ments explain in detail because the first sentence creates summary sections of the generated documentation. So, these are the basics of using the javadoc util- ity, how do you actually generate the documentation? At your command prompt, type the javadoc command using the following syntax: javadoc [options] [package-names] [source-files] TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  20. JavaProgAbsBeg-12.qxd 2/25/03 8:58 AM Page 437 437 TA B L E 1 2 . 2 JAVADOC TA G S Chapter 12 Tag Arguments Description @author author_name Specifies the author’s name. @deprecated deprecated_text Adds a comment that specifies that the code is deprecated. Creating Your Own Components and Packages {@link package.name#member label} (appears in the Creates a hyperlink to the braces) specified member’s documentation and uses the given label. @param parameter_name Describes parameters of description methods. @throws exception Generates a comment that description specifies which exceptions the method throws (same as @exception). @version version_text Generates a comment indicating the version you specify. The only options you’re going to use in this chapter are these: • –d specifies which directory to put the documentation into. • -author makes sure you know how to specify yourself as the author of your packages. • –version shows you how to make the javadoc utility include the version you specify using the @version javadoc command. The author and version information are left out by default even if the tags are in the source file’s javadoc comments. A more real example is: javadoc –d docs –author -version pkg.mypackage This generates the documentation for a package named pkg.mypackage. The doc- umentation will be placed in the docs directory (specified by the –d option) and will include the author and version information. There is actually much more information to learn about javadoc. This chapter only covers the basic essentials, so you’ll have to refer to the tool documentation, which is included in the API documentation download package, to expand your knowledge from here. You know all you need to know for documenting the jpr.lightweight package. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2