Thinking in Java 3rd Edition phần 9 doc

119 365 0
Thinking in Java 3rd Edition phần 9 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

922 Thinking in Java www.BruceEckel.com Once you have your Bean properly inside a JAR file you can bring it into a Beans-enabled program-builder environment. The way you do this varies from one tool to the next, but Sun provides a freely available test bed for JavaBeans in their “Bean Builder.” (Download from java.sun.com/beans.) You place a Bean into the Bean Builder by simply copying the JAR file into the correct subdirectory. Feedback More complex Bean support You can see how remarkably simple it is to make a Bean, but you aren’t limited to what you’ve seen here. The JavaBeans architecture provides a simple point of entry but can also scale to more complex situations. These situations are beyond the scope of this book, but they will be briefly introduced here. You can find more details at java.sun.com/beans. Feedback One place where you can add sophistication is with properties. The examples above have shown only single properties, but it’s also possible to represent multiple properties in an array. This is called an indexed property. You simply provide the appropriate methods (again following a naming convention for the method names) and the Introspector recognizes an indexed property so your application builder tool can respond appropriately. Feedback Properties can be bound, which means that they will notify other objects via a PropertyChangeEvent. The other objects can then choose to change themselves based on the change to the Bean. Feedback Properties can be constrained, which means that other objects can veto a change to that property if it is unacceptable. The other objects are notified using a PropertyChangeEvent, and they can throw a PropertyVetoException to prevent the change from happening and to restore the old values. Feedback You can also change the way your Bean is represented at design time: Feedback 1. You can provide a custom property sheet for your particular Bean. The ordinary property sheet will be used for all other Beans, but yours is automatically invoked when your Bean is selected. Feedback Chapter 14: Creating Windows & Applets 923 2. You can create a custom editor for a particular property, so the ordinary property sheet is used, but when your special property is being edited, your editor will automatically be invoked. Feedback 3. You can provide a custom BeanInfo class for your Bean that produces information that’s different from the default created by the Introspector. Feedback 4. It’s also possible to turn “expert” mode on and off in all FeatureDescriptors to distinguish between basic features and more complicated ones. Feedback More to Beans There are a number of books about JavaBeans; for example, JavaBeans by Elliotte Rusty Harold (IDG, 1998). Feedback Summary Of all the libraries in Java, the GUI library has seen the most dramatic changes from Java 1.0 to Java 2. The Java 1.0 AWT was roundly criticized as being one of the worst designs seen, and while it would allow you to create portable programs, the resulting GUI was “equally mediocre on all platforms.” It was also limiting, awkward, and unpleasant to use compared with the native application development tools available on a particular platform. Feedback When Java 1.1 introduced the new event model and JavaBeans, the stage was set—now it was possible to create GUI components that could be easily dragged and dropped inside visual application builder tools. In addition, the design of the event model and JavaBeans clearly shows strong consideration for ease of programming and maintainable code (something that was not evident in the 1.0 AWT). But it wasn’t until the JFC/Swing classes appeared that the job was finished. With the Swing components, cross-platform GUI programming can be a civilized experience. Feedback Actually, the only thing that’s missing is the application builder tool, and this is where the real revolution lies. Microsoft’s Visual Basic and Visual C++ require Microsoft’s application builder tools, as does Borland’s 924 Thinking in Java www.BruceEckel.com Delphi and C++ Builder. If you want the application builder tool to get better, you have to cross your fingers and hope the vendor will give you what you want. But Java is an open environment, and so not only does it allow for competing application builder environments, it encourages them. And for these tools to be taken seriously, they must support JavaBeans. This means a leveled playing field: if a better application builder tool comes along, you’re not tied to the one you’ve been using— you can pick up and move to the new one and increase your productivity. This kind of competitive environment for GUI application builder tools has not been seen before, and the resulting marketplace can generate only positive results for the productivity of the programmer. Feedback This chapter was meant only to give you an introduction to the power of Swing and to get you started so you could see how relatively simple it is to feel your way through the libraries. What you’ve seen so far will probably suffice for a good portion of your UI design needs. However, there’s a lot more to Swing—it’s intended to be a fully powered UI design tool kit. There’s probably a way to accomplish just about everything you can imagine. Feedback If you don’t see what you need here, delve into the JDK documentation from Sun and search the Web, and if that’s not enough then find a dedicated Swing book—a good place to start is The JFC Swing Tutorial, by Walrath & Campione (Addison Wesley, 1999). Feedback Exercises Solutions to selected exercises can be found in the electronic document The Thinking in Java Annotated Solution Guide, available for a small fee from www.BruceEckel.com. 1. Create an applet/application using the Console class as shown in this chapter. Include a text field and three buttons. When you press each button, make some different text appear in the text field. Feedback 2. Add a check box to the applet created in Exercise 1, capture the event, and insert different text into the text field. Feedback 3. Create an applet/application using Console. In the JDK documentation from java.sun.com, find the JPasswordField Chapter 14: Creating Windows & Applets 925 and add this to the program. If the user types in the correct password, use Joptionpane to provide a success message to the user. Feedback 4. Create an applet/application using Console, and add all the Swing components that have an addActionListener( ) method. (Look these up in the JDK documentation from java.sun.com. Hint: use the index.) Capture their events and display an appropriate message for each inside a text field. Feedback 5. Create an applet/application using Console, with a JButton and a JTextField. Write and attach the appropriate listener so that if the button has the focus, characters typed into it will appear in the JTextField. Feedback 6. Create an applet/application using Console. Add to the main frame all the components described in this chapter, including menus and a dialog box. Feedback 7. Modify TextFields.java so that the characters in t2 retain the original case that they were typed in, instead of automatically being forced to upper case. Feedback 8. Locate and download one or more of the free GUI builder development environments available on the Internet, or buy a commercial product. Discover what is necessary to add BangBean to this environment and to use it. Feedback 9. Add Frog.class to the manifest file as shown in this chapter and run jar to create a JAR file containing both Frog and BangBean. Now either download and install the Bean Builder from Sun or use your own Beans-enabled program builder tool and add the JAR file to your environment so you can test the two Beans. Feedback 10. Create your own JavaBean called Valve that contains two properties: a boolean called “on” and an int called “level.” Create a manifest file, use jar to package your Bean, then load it into the Bean Builder or into a Beans-enabled program builder tool so that you can test it. Feedback 926 Thinking in Java www.BruceEckel.com 11. Modify MessageBoxes.java so that it has an individual ActionListener for each button (instead of matching the button text). Feedback 12. Monitor a new type of event in TrackEvent.java by adding the new event handling code. You’ll need to discover on your own the type of event that you want to monitor. Feedback 13. Inherit a new type of button from JButton. Each time you press this button, it should change its color to a randomly-selected value. See ColorBoxes.java for an example of how to generate a random color value. Feedback 14. Modify TextPane.java to use a JTextArea instead of a JTextPane. Feedback 15. Modify Menus.java to use radio buttons instead of check boxes on the menus. Feedback 16. Simplify List.java by passing the array to the constructor and eliminating the dynamic addition of elements to the list. Feedback 17. Modify SineWave.java to turn SineDraw into a JavaBean by adding “getter” and “setter” methods. Feedback 18. Remember the “sketching box” toy with two knobs, one that controls the vertical movement of the drawing point, and one that controls the horizontal movement? Create one of those, using SineWave.java to get you started. Instead of knobs, use sliders. Add a button that will erase the entire sketch. Feedback 19. Starting with SineWave.java, create a program (an applet/application using the Console class) that draws an animated sine wave that appears to scroll past the viewing window like an oscilloscope, driving the animation with a Thread. The speed of the animation should be controlled with a java.swing.JSlider control. Feedback 20. Modify Exercise 19 so that multiple sine wave panels are created within the application. The number of sine wave panels should be controlled by HTML tags or command-line parameters. Feedback Chapter 14: Creating Windows & Applets 927 21. Modify Exercise 19 so that the java.swing.Timer class is used to drive the animation. Note the difference between this and java.util.Timer. Feedback 22. Create an “asymptotic progress indicator” that gets slower and slower as it approaches the finish point. Add random erratic behavior so it will periodically look like it’s starting to speed up. Feedback 23. Modify Progress.java so that it does not share models, but instead uses a listener to connect the slider and progress bar. Feedback 24. Follow the instructions in the section titled “Packaging an applet into a JAR file” to place TicTacToe.java into a JAR file. Create an HTML page with the simple version of the applet tag along with the archive specification to use the JAR file. Run HTMLconverter on file to produce a working HTML file. Feedback 25. Create an applet/application using Console. This should have three sliders, one each for the red, green, and blue values in java.awt.Color. The rest of the form should be a JPanel that displays the color determined by the three sliders. Also include non-editable text fields that show the current RGB values. Feedback 26. In the JDK documentation for javax.swing, look up the JColorChooser. Write a program with a button that brings up the color chooser as a dialog. Feedback 27. Almost every Swing component is derived from Component, which has a setCursor( ) method. Look this up in the JDK documentation. Create an applet and change the cursor to one of the stock cursors in the Cursor class. Feedback 28. Starting with ShowAddListeners.java, create a program with the full functionality of c10:ShowMethods.java. Feedback 29. Turn c12:TestRegularExpression.java into an interactive Swing program that allows you to put an input string in one TextArea and a regular expression in a TextField. The results should be displayed in a second TextArea. 928 Thinking in Java www.BruceEckel.com 30. Modify InvokeLaterFrame.java to use invokeAndWait( ). 929 15: Discovering problems Before C was tamed into ANSI C, we had a little joke: “my code compiles, so it should run!” (Ha ha!). This was funny only if you understood C, because at that time the C compiler would accept just about anything—C was truly a “portable assembly language,” created to see if it was possible to develop a portable operating system (Unix) that could be moved from one machine architecture to another without rewriting it from scratch in the new machine’s assembly language. So C was actually created as a side effect of building Unix, and not as a general-purpose programming language. Feedback Because C was targeted at programmers who wrote operating systems in assembly language, it was implicitly assumed that those programmers knew what they were doing and didn’t need safety nets. For example, assembly-language programmers didn’t need the compiler to check argument types and usage, and if they decided to use a data type in a different way than it was originally intended, they certainly must have good reason to do so, and the compiler didn’t get in the way. Thus, getting your pre-ANSI C program to compile was only the first step in the long process of developing a bug-free program. Feedback The development of ANSI C along with stronger rules about what the compiler would accept came after lots of people used C for projects other than writing operating systems, and after the appearance of C++ which greatly improved your chances of having a program run decently once it compiled. Much of this improvement came through strong static type checking: “strong,” because the compiler prevented you from abusing the type, “static” because ANSI C and C++ perform type checking at compile time. Feedback 930 Thinking in Java www.BruceEckel.com To many people (myself included), the improvement was so dramatic that it appeared that strong static type checking was the answer to a large portion of our problems. Indeed, one of the motivations for Java was that C++’s type checking wasn’t strong enough (primarily because C++ had to be backward-compatible with C, and so was chained to its limitations). Thus Java has gone even further to take advantage of the benefits of type checking, and since Java has language-checking mechanisms that exist at run time (C++ doesn’t; what’s left at run time is basically assembly language—very fast, but with no self-awareness) it isn’t restricted to only static type checking 1 . Feedback It seems, however, that language-checking mechanisms can take us only so far in our quest to develop a correctly-working program. C++ gave us programs that worked a lot sooner than C programs, but often still had problems like memory leaks and subtle, buried bugs. Java went a long way towards solving those problems, and yet it’s still quite possible to write a Java program containing nasty bugs. In addition (despite the amazing performance claims always touted by the flaks at Sun) all the safety nets in Java added additional overhead, so sometimes we run into the challenge of getting our Java programs to run fast enough for a particular need (although it’s usually more important to have a working program than one that runs at a particular speed). Feedback This chapter presents tools to solve the problems that the compiler doesn’t. In a sense, we are admitting that the compiler can only take us so far in the creation of robust programs, and so we are moving beyond the compiler and creating a build system and code that know more about what a program is and isn’t supposed to do. Feedback 1 It is primarily oriented to static checking, however. There is an alternative system, called latent typing or dynamic typing or weak typing, in which the type of an object is still enforced, but it is enforced at run time, when the type is used, rather than at compile time. Writing code in such a language—Python (http://www.python.org) is an excellent example—gives the programmer much more flexibility and requires far less verbiage to satisfy the compiler, and yet still guarantees that objects are used properly. However, to a programmer convinced that strong, static type checking is the only sensible solution, latent typing is anathema and serious flame wars have resulted from comparisons between the two approaches. As someone who is always in pursuit of greater productivity, I have found the value of latent typing to be very compelling. In addition, the ability to think about the issues of latent typing help you, I believe, to solve problems that are difficult to think about in strong, statically typed languages. Chapter 15: Discovering problems 931 One of the biggest steps forward is the incorporation of automated unit testing. This means writing tests and incorporating those tests into a build system that compiles your code and runs the tests every single time, as if the tests were part of the compilation process (you’ll soon start relying upon them as if they are). For this book, a custom testing system was developed to ensure the correctness of the program output (and to display the output directly in the code listing), but the defacto standard JUnit testing system will also be used when appropriate. To make sure that testing is automatic, tests are run as part of the build process using Ant, an open-source tool that has also become a defacto standard in Java development, and CVS, another open-source tool that maintains a repository containing all your source code for a particular project. Feedback JDK 1.4 introduced an assertion mechanism to aid in the verification of code at run time. One of the more compelling uses of assertions is Design by Contract (DBC), a formalized way to describe the correctness of a class. In conjunction with automated testing, DBC can be a powerful tool. Feedback Sometimes unit testing isn’t enough, and you need to track down problems in a program that runs, but doesn’t run right. In JDK 1.4, the logging API was introduced to allow you to easily report information about your program. This is a significant improvement over adding and removing println( ) statements in order to track down a problem, and this section will go into enough detail to give you a thorough grounding in this API. This chapter also provides an introduction to debugging, showing the information a typical debugger can provide to aid you in the discovery of subtle problems. Finally, you’ll learn about profiling and how to discover the bottlenecks that cause your program to run too slowly. Feedback Unit Testing A recent realization in programming practice is the dramatic value of unit testing. This is the process of building integrated tests into all the code that you create, and running those tests every time you do a build. That way, the build process can check for more than just syntax errors, since you teach it how to check for semantic errors as well. C-style [...]... numOfLines++; console.println(x); fout.println(x); } public void print(char x) { console.print(x); fout.print(x); } public void println(char x) { numOfLines++; console.println(x); fout.println(x); } public void print(int x) { console.print(x); fout.print(x); } public void println(int x) { numOfLines++; console.println(x); fout.println(x); } public void print(long x) { console.print(x); fout.print(x);... void print(char[] x) { console.print(x); fout.print(x); } public void println(char[] x) { numOfLines++; console.println(x); fout.println(x); } public void print(String x) { console.print(x); fout.print(x); } public void println(String x) { numOfLines++; console.println(x); fout.println(x); } public void print(Object x) { console.print(x); fout.print(x); } public void println(Object x) { numOfLines++;... void println(long x) { numOfLines++; console.println(x); fout.println(x); } public void print(float x) { console.print(x); fout.print(x); } public void println(float x) { numOfLines++; console.println(x); fout.println(x); } public void print(double x) { console.print(x); fout.print(x); } Chapter 15: Discovering problems 93 7 public void println(double x) { numOfLines++; console.println(x); fout.println(x);... println(Object x) { numOfLines++; console.println(x); fout.println(x); } public void println() { if(false) console.print("println"); numOfLines++; console.println(); fout.println(); } public void write(byte[] buffer, int offset, int length) { console.write(buffer, offset, length); fout.write(buffer, offset, length); } public void write(int b) { 93 8 Thinking in Java www.BruceEckel.com console.write(b);... running the code Naturally, I understood this and took some early faltering steps towards implementing a system that would perform automatic execution tests, but I had succumbed to publishing schedules, all the while knowing that there was definitely something wrong with my 93 2 Thinking in Java www.BruceEckel.com process and that it would come back to bite me in the form of embarrassing bug reports (in. .. produces input on demand: System.setIn(new BufferedInputStream(new InputStream(){ char[] input = ("test\n").toCharArray(); int index = 0; public int read() { return (int)input[index = (index + 1) % input.length]; } })); this.className = className; openOutputFile(); } // public PrintStream getConsole() { return console; } public void dispose() { System.setOut(console); System.setErr(err); System.setIn(stdin);... insights and new ideas 4 Inspired by Python’s doctest module 93 4 Thinking in Java www.BruceEckel.com extends SimpleTestException { public NumOfLinesException(int exp, int out) { super("Number of lines of output and " + "expected output did not match.\n" + "expected: \n" + "output: lines)"); } } ///:~ Or, the number of lines might be correct, but one or more lines might not match:...programming languages, and C++ in particular, have typically valued performance over programming safety The reason that developing programs in Java is so much faster than in C++ (roughly twice as fast, by most accounts) is because of Java s safety net: features like garbage collection and improved type checking By integrating unit testing into your build process, you can extend this safety net, resulting in. .. method, which takes as arguments an array of Objects containing expected output lines and an int containing various flags Flags are implemented using bit shifting, with each bit corresponding to a particular flag as defined at the beginning of Test .java Feedback The expect( ) method first inspects the flags argument to see if it should delay processing to allow a slow program to catch up It then calls... JUnit but instead is used by other tests in the class As long as 95 0 Thinking in Java www.BruceEckel.com the method name doesn’t begin with “test,” JUnit doesn’t run it or expect it to have a particular signature Here, compare( ) is private to emphasize that it is only used within the test class, but it could also be public The remaining test methods eliminate duplicate code by refactoring it into the . second TextArea. 92 8 Thinking in Java www.BruceEckel.com 30. Modify InvokeLaterFrame .java to use invokeAndWait( ). 92 9 15: Discovering problems Before C was tamed into ANSI C, we had. console.print(x); fout.print(x); } 93 8 Thinking in Java www.BruceEckel.com public void println(double x) { numOfLines++; console.println(x); fout.println(x); } public void print(char[]. println(char x) { numOfLines++; console.println(x); fout.println(x); } public void print(int x) { console.print(x); fout.print(x); } public void println(int x) { numOfLines++;

Ngày đăng: 14/08/2014, 00:21

Từ khóa liên quan

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

Tài liệu liên quan