Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 64 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
64
Dung lượng
8,73 MB
Nội dung
2. Create the source to use for your template—Start with one of the NetBeans templates, then modify it to meet your needs, or create completely new source code. 3. Save the source as a template—Start in the Explorer window, right click the source, select Save as Template from the context menu, and select the template category from the Save As Template dialog. Chapter 9. GUI Building 170 And here are the steps for making a custom GUI component: 1. Optionally, create your own Component Palette tab—From the main window select Tools->Options. Open nodes IDE Configuration node, then Look and Feel. Right click the Component Palette node, then select Add Palette Category from context menu. Name the new category, and click OK. 2. Create or locate the new component—It's just a Java Bean. Use an existing bean, or write your own. See the next chapter for more on beans. 3. Add the new component to the Component Palette, then customize it. We will take a closer look at adding components to the Component Palette in the next chapter, after creating our own Java Bean component. Containers within Containers A JPanel can contain any number of components. Since a JPanel is itself a component, it can be contained within a another JPanel, a JFrame, or any other GUI container. As we will see in the next section, this can be a powerful technique for building complex GUIs. But there's a potential editing problem with components in containers within containers. If all the components in all the containers were visible at the same time, it could become visually confusing and unmanageable. The Form Editor prevents such confusion by showing only one container with its components at a time, and by enabling the developer to choose which container to show. Let's walk through a short demonstration to see how it works. Notice the empty space in the upper right corner of our AddStrings example. Let's fill the space with a JPanel, then put a couple of GUI components into the JPanel, just to demonstrate what's possible. Select the JPanel icon in the Component Pallet, then drop it into the empty corner of AddStrings in the Form Editor. It shows up as a small blue square, much too small to be useful. We'll fix that by using the GridBag Customizer to adjust the space it occu- pies. Right click GridBagLayout in the Component Inspector, then select Customize from the context menu. Select the JPanel in the Customizer Dialog window, then adjust GridWidth to 3 and GridHeight to 2. Close the Customizer and turn your attention back to the Form Editor. Where's our JPanel? The little blue square has vanished, and the space just looks blank in the Form Editor. No prob- lem, the JPanel still there in the Component Inspector. Select it in the Component Inspector, and the blue square reappears. The JPanel was just hidden, and selecting it in the Component Inspector brought it to the fore in the Form Editor. Right click the JPanel in the Component Inspector, then select Design This Container from the context menu. Now the JPanel takes over all the space, and the JFrame disappears! Drop in a few components from the Component Palette—A JButton or two, maybe a JLabel—whatever you like just to get something visible in the JPanel. Then compile and execute to see what you've done. Not fancy, but it opens up a world of possibilities. By allowing the developer to put containers within containers, and by focusing the Form Editor on one container and its components at a time, NetBeans allows unlimited complexity in GUI design, and keeps the complexity manageable. Go back to the Form Editor, which has the JPanel visible. Right click, and examine the context menu. Now the choices include Design This Container and Design Top Container. This gives you an easy way to switch back and forth with either the JFrame or JPanel in the foreground. Building Complex GUIs Chapter 9. GUI Building 171 When you create a complex GUI with many components, it can be difficult to make them behave properly. Trying to control the size and placement of even a few components can be like herding cats; focus your attention on one, and the others run amok. As we have seen, GridBagLayout is often your best hope for managing multiple components in a sin- gle container. But there's another way. Instead of struggling with too many components in one container, use the con- tainers within containers technique to build a GUI that's many layers deep with just a few components in each layer. Create a container, say a JPanel, then add just a few components to the container, few enough that you can easily control their size and placement. Use the container in constructing the next layer of your complex GUI. For greater flexibility in testing and reuse, and for a cleaner design, you may choose to turn the container with its components into a Java Bean. This is exactly where we're headed with the AddStrings example. We will place a manageable number of components into a JPanel container, then turn the JPanel into a Bean. We will add our new Bean to a JFrame container and use the Bean properties to configure it. Of course, if you're only creating a Bean as an intermediate com- ponent for one project, then you won't need to do everything that will be done in the Java Beans chapter—create a BeanInfo class, link it to an icon, and add it to your Component Palette. Giving your intermediate containers a few basic Bean features will be enough to greatly simplify your GUI building task. By now our AddStrings example is looking good and running smoothly. But it's a standalone application. The only way other users could benefit from using the application would be to install it, launch it every time they wanted to use it, and then explicitly exit when they're done. If we convert the application into a component that other developers can include in larger applications, then it can be used much more widely and easily. So, in the next chapter, we will build a Java Bean around the essential feature of AddStrings. Then anyone using Java to build a complex GUI can drop AddStrings into their form with just a few mouse clicks. Chapter 9. GUI Building 172 Chapter 10. Java Beans Table of Contents Why Should I Make Beans? 173 CreatingJavaBeans 173 CreatingaGUIComponent 174 Converting a GUI Component into a Bean 176 Adding an Event Set to a Bean 179 GeneratingaBeanInfo Class 181 AddingaDesign-Time Icon 183 ComponentPalette 183 Adding a Category to the Component Palette 183 Adding a Bean to the Component Palette 184 ComponentPaletteProblems 185 Why Should I Make Beans? You should make Java Beans to encourage reuse of your Java code. JavaBeans is the standard architecture for building reusable components in Java. Originally intended as visual components for building GUIs, now the Java Beans are widely used in all Java environments, including JSP and EJB development. Like components in other object oriented programming languages, Java Beans have properties that can be set at design time by visual design tools, or at run time by the containing program. If you want other developers to use your code, if you want your components to snap together with ease, if you want to spend your time developing application logic instead of debugging interfaces, then make Java Beans. For a deeper un- derstanding of the JavaBeans architecture, see Sun's JavaBeans[TM] Technology [http://java.sun.com/beans] page, or read Developing Java Beans (O'Reilly). Creating Java Beans We will continue with the AddStrings example from the GUI Building chapter to demonstrate NetBeans features for developing Java Beans. It is not necessary to go through all this to create a Bean from scratch. Simply follow the procedure for creating a New Java object, and use the Bean template. We're taking the long route to show more ways that NetBeans can help. Here's the plan: 1. Create a GUI component from the AddStrings JFrame. 2. Convert the component into a proper Bean. 3. Add an event set to inform the container about changes to Bean properties. 4. Generate a BeanInfo class to support using the Bean in a visual design tool, such as NetBeans. • Generate the BeanInfo class. Chapter 10. Java Beans 173 • Launch and use the BeanInfo Editor. • Add a design time Icon. 5. Add your own category to the NetBeans Component Palette. 6. Add the Bean to your Component Palette category. 7. Use the Bean in GUI construction. Next, we will go through the steps for this plan in detail. With any application, the functional decomposition necessary to create usable components from the application's logic requires analytical skill and care. But once you've decided what to include in each component, the process of creating Java Beans from application code is straightforward. We will go through the process more thoroughly than you may choose to do in actual practice, just to give a complete pic- ture of what's possible. Creating a GUI Component A GUI component is an object that can be placed in a GUI container. A JFrame is a container, but is not a component and cannot be placed in a container. A JPanel is both a container and a component, so it can contain other compo- nents, and it can be placed in a container. We based our original AddStrings example on a JFrame to make testing easy, because a JFrame is a top level window that can be executed alone. But the JFrame version of AddStrings cannot be used as a component. Therefore, the first step in creating an AddStrings Java Bean is to create an AddStrings JPanel with the same components and logic as the original JFrame example from the previous chap- ter. 1. Let's keep the name AddStrings for the component we are creating. We need to avoid a name conflict between the new AddStrings JPanel and the old AddStrings JFrame. So our example uses a new package named Beans. You could also rename or move the old JFrame. 2. Create a JPanel named AddStrings in the new Beans package. Change the layout manager to GridBagLay- out. 3. Open both the old and new AddStrings objects by double clicking their nodes in the Explorer. Open the Form AddStrings node for both objects, then the JPanel and JFrame nodes to expose their components. 4. Select and copy the JLabel and JTextField components from the JFrame (see Figure 10.1). Don't bother with the JMenu components, because they aren't needed for the Bean that we're creating. Figure 10.1. Copying AddStrings components Chapter 10. Java Beans 174 5. Paste the components copied from the JFrame in the GuiDemoAdvanced package into the JPanel in the Beans package. You may close the old AddStrings JFrame. 6. In the new JPanel create ActionPerformed events for JTextFields tbA and tbB. Fill in the handling code for each event. While we're at it, let's extract the common code into a convenience method named up- dateTfSum, creating the code shown in Example 10.1. The new AddStrings JPanel isn't a Bean yet, but it is a component that we can use in GUI building. Example 10.1. Code in AddStrings JFrame needed for the new Bean Chapter 10. Java Beans 175 private void tfAActionPerformed(java.awt.event.ActionEvent evt) { // Add your handling code here: updateTfSum(); } private void tfBActionPerformed(java.awt.event.ActionEvent evt) { // Add your handling code here: updateTfSum(); } private void updateTfSum(){ tfSum.setText(tfA.getText() + tfB.getText()); } Compile and continue to the next step. Don't try to execute the compiled class, because the JPanel doesn't have a main. 7. Let's test it! We will add the JPanel component to a JFrame, then execute the JFrame. a. Create a new JFrame named ASTest1. b. In the Explorer (not the Component Inspector) open the nodes of the JFrame to expose its components. c. Copy the JPanel to the system clipboard—right click the highest level node of the new AddStrings JPanel, then select Copy from the context menu. d. Paste the JPanel into the JFrame—right click the JFrame level of ASTest1, then select Paste from the context menu. This adds AddStrings as a component in ASTest1. 8. Compile and Execute ASTest1. You will see the AddStrings GUI, familiar from the previous chapter. We will continue working with the same AddStrings source as we develop our example. For reference, the author has saved a copy at this stage named AddStrings_1. To make it easy to follow the process of creating an AddStrings Bean, intermediate source has been saved at several stages and is available for download from the O'Reilly website [http://www.oreilly.com/]. Converting a GUI Component into a Bean A bare bones Bean doesn't need much. It needs to be serializable, to have a no-argument constructor, and at least one property with public getter and setter methods. Our Bean will be a bit more interesting, but we'll start by giving it the bare essentials. 1. A Bean must be serializable, so modify the AddStrings class declaration to the following. public class AddStrings extends javax.swing.JPanel implements java.io.Serializable { 2. AddStrings already has a no-argument constructor, so we don't need to do anything to meet that requirement. 3. Let's add some Bean properties. Open nodes in the Explorer from the top level AddStrings object down through the class AddStrings node to Bean Patterns. We will add Bean properties that correspond to the text fields in Chapter 10. Java Beans 176 AddStrings. Right click Bean Patterns, select Add, then select Property to launch the Bean Property wizard. Fill in the wizard properties as shown in Table 10.1. This requires using the wizard three times for the three text fields in AddStrings. 4. Now we have a valid Bean, but the properties aren't worth much because they aren't connected to anything. Mod- ify the getter and setter methods as shown in Example 10.2. Just add the lines from the following code sample that have the comment /*connect property to field*/. Notice that the read only property textSum does not store its value in a separate field. Its getter method just calculates the value when it's needed: Example 10.2. Code Needed in Getter and Setter methods for AddStrings Bean /** Getter for property textA. * @return Value of property textA. */ public String getTextA() { return this.textA; } /** Setter for property textA. * @param textA New value of property textA. */ public void setTextA(String textA) { this.textA = textA; tfA.setText(this.textA);/*connect property to field*/ updateTfSum();/*connect property to field*/ } /** Getter for property textB. * @return Value of property textB. */ public String getTextB() { return this.textB; } /** Setter for property textB. * @param textB New value of property textB. */ public void setTextB(String textB) { this.textB = textB; tfB.setText(this.textB);/*connect property to field*/ updateTfSum();/*connect property to field*/ } /** Getter for property textSum. * @return Value of property textSum. */ public String getTextSum() { return tfSum.getText();/*connect property to field*/ } Compile and continue to the next step. 5. Now that our component is a Bean, it's time to test it again. One quick way to test it is similar to the BeanBox that comes with the JavaBeansTM Development Kit (BDK) from Sun Microsystems. Right click AddStrings in the Ex- plorer, then select Customize Bean from the context menu. Two windows will open—a Bean properties editor, and a Bean test window. This should be sufficient for testing during normal development. The Customize Bean tool also provides a way to set property values and save the results as a serialized object. Chapter 10. Java Beans 177 But we will continue building test drivers to demonstrate the Bean in a more realistic context. Create a new JFrame named ASTest2. Open its nodes in the Explorer to expose the components in the JFrame. Right click the highest level AddStrings node in the Explorer, then select Copy from the context menu. Right click the JFrame level of ASTest2, then select Paste from the context menu. So far it's like the previous test driver, ASTest1. Next, add two JTextField components and one JLabel. Be sure to add them to the JFrame and not to addStrings1. Keep the default names for the components, then use the Layout tab in the Component Inspector to set their Direction property in the default BorderLayout as shown in Table 10.2. Use the Events tab in the Component Inspector to add ActionPerformed event handler methods for the two JTextFields. Add method body code as shown in Example 10.3. The added lines use the Bean's setter methods to modify its TextA and TextB properties. Example 10.3. Event Handler Methods in AddStrings Bean private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) { // Add your handling code here: addStrings1.setTextA(jTextField1.getText()); jLabel1.setText(jTextField1.getText() + jTextField2.getText()); } private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) { // Add your handling code here: addStrings1.setTextB(jTextField2.getText()); jLabel1.setText(jTextField1.getText() + jTextField2.getText()); } 6. We aren't finished with AddStrings yet, but we've done enough to test it as a Bean. Compile and execute ASTest2. It should look like Figure 10.2. Figure 10.2. Testing the AddStrings Bean The lower part of the window shows the familiar AddStrings GUI. The text fields in the upper part allow us to test AddStrings as a Bean. When you change information in the upper text fields, the corresponding Bean properties and the associated AddStrings fields are also changed. But we're only half done, because changing Chapter 10. Java Beans 178 AddStrings fields should also change the upper ASTest2 fields. As before, the author has saved a reference copy at this stage named AddStrings_2 that is available for download from the O'Reilly website [http://www.oreilly.com/]. Adding an Event Set to a Bean Next, we'll turn the Read/Write properties of AddStrings into bound properties. That means any change to a prop- erty will fire an event to inform listening objects about the change. We will use this to update the upper text fields in our test driver when the AddStrings fields are changed. This is only one way for our Bean to inform listeners about property changes. As you step through the process, you'll glimpse other options and get a sense of what's possible with NetBeans. 1. Again, open nodes in the Explorer from the top level AddStrings object down through the class AddStrings node to Bean Patterns. Right click Bean Patterns, select Add, then select Multicast Event Source to launch the Event Set wizard. Fill in the wizard properties as shown in Table 10.3. 2. The event processing code that was added needs customization before it will do the job. a. Remove the following line from the tfAActionPerformed and tfBActionPerformed methods. updateTfSum(); b. Add the lines from Example 10.4 that have the comment /*needed for event*/. Example 10.4. Code Needed for Events in AddStrings Bean private void tfAActionPerformed(java.awt.event.ActionEvent evt) { // Add your handling code here: setTextA(tfA.getText());/*needed for event*/ } private void tfBActionPerformed(java.awt.event.ActionEvent evt) { // Add your handling code here: setTextB(tfB.getText());/*needed for event*/ } private void updateTfSum(){ tfSum.setText(tfA.getText() + tfB.getText()); } /** Getter for property textA. * @return Value of property textA. */ public String getTextA() { return this.textA; } /** Setter for property textA. * @param textA New value of property textA. */ public void setTextA(String textA) { String oldTextA = this.textA;/*needed for event*/ Chapter 10. Java Beans 179 [...]... look in the IDE A 16x16 icon, AddStrings.gif, has been included with the source examples for this book Figure 10 .4 is an enlarged view Figure 10 .4 The AddStrings Bean icon In the BeanInfo Editor select the topmost node, named simply BeanInfo Fill in the Icon 16x16 Color property with the classpath to the icon If you want help getting the classpath right, then click the ellipsis button ( ) to open the Icon... select the word "getString" in the text editor then hit Alt-F1 The search tool will be launched with "getString" as the query string and the results of the query showing in the list in the left section of the tool's window This process is illustrated in Figure 11.3 and Figure 11 .4 The same effect is achieved by right clicking on a word in the Source Editor and selecting Tools->Show Javadoc from the 188... in the Javadocs of one class to the Javadoc of another using the @link tag The IDE allows you to specify links to other generated Javadocs by using the Doclet's Link and Link Offline properties The difference between these properties is that the former requires a path to a directory where a package-list file can be found while the latter does not require the package-list files to be existent at the. .. compare the tree view to the text view, you'll find the elements and attributes in the data section match up, one to one in the same order But the DTD section is different In the tree view all the elements are listed first under the ElementDeclLayer node, and the attributes are listed separately under AttlistDeclLayer The difference is determined by the document's Node View setting To access the Node... Select the "celcius" parameter from the drop down box, and type in a description of the parameter in the text box You also have to add tags for the return value and the Exception The steps for adding these are quite similar For the return value you need to select the "@return" radio box, and for the exception you will need to select "@throws" Once you've completed all editing, you can click the Refresh... it? 1 84 Chapter 10 Java Beans For the final test, let's set the Bean's properties Double click ASTest4 in the Explorer to open it in the Component Inspector Open the JFrame node in the Component Inspector to expose its components Select AddStrings to expose its properties Only textA and textB are available They are the writeable properties that were selected to include in the BeanInfo class Give them... Auto-Commenting Tool To launch the Auto Commenting Tool, open the Java source file in the editor, right click on the opened file and select Tools->Auto Comment You should now see a dialog box similar to the one shown in Figure 11.5 The tool lists all the classes, methods and fields in the the Java file and allows you to view and correct the Javadoc comments The tool also points out which of these elements have... (as in Figure 12 .4) , Right click the top Inventory node, select Properties from the context menu, and click the View tab Figure 12 .4 DTD and data nodes Try out the different views The Linear Node View shows DTD element and attribute declarations in the same order as the text document The Data Only Node View has the same order, but hides comments and processing instructions You can set the node view at... Javadoc HTML files in the specified directory The executor will format the HTML files based on the preconfigured doclet that is specified in the Doclets property Additional source files can be added to your generated Javadocs if you specify them in the Extdirs property Any Java files found in these directories will be processed by the executor and the resulting html files copied to the specified output... from the Component Palette Did you wipe out the compiled class file and reopen NetBeans? The component palette can't show a Bean that has no class file Does your Bean no longer have the icon you assigned it? Perhaps you generated a BeanInfo class for your Bean, but didn't compile it The BeanInfo class is the link from the icon to the IDE The source examples with this book must be compiled before the . click the right spot in the Component Palette, then select Create New Category from the context menu. What exactly is the right spot? Try the empty space to the right of the last tab for the existing. sure to add them to the JFrame and not to addStrings1. Keep the default names for the components, then use the Layout tab in the Component Inspector to set their Direction property in the default. Java Beans 1 74 5. Paste the components copied from the JFrame in the GuiDemoAdvanced package into the JPanel in the Beans package. You may close the old AddStrings JFrame. 6. In the new JPanel