Change the name of the list from jList to jListCustomers and change its gridy property you have to expand constraint from -1 to 1 Figure 14-33.. Figure 14-34 Sample GUI: stage 3 In case
Trang 1Now select a JList of the Swing components from the palette and drop the list on the jPanelLeft This component allows the user to select one or more objects from a list
Change the name of the list from jList to jListCustomers and change its gridy
property (you have to expand constraint) from -1 to 1 (Figure 14-33)
Figure 14-33 JList constraints Changing the gridy property aligns the JList below the JLabel within the jPanelLeft bean
You also have to change the property selectionMode from its initial value
MULTIPLE_INTERVAL to SINGLE This prevents us from selecting multiple elements from the list bean
By now the GUI should look as shown in Figure 14-34
Tip: The gridy property is used to set the vertical position of objects, where the topmost cell has gridy=0
Trang 2Figure 14-34 Sample GUI: stage 3
In case our list contains many entries, it is a good idea to have a scroll bar added
to the list bean
To do this, you need to select the JScrollPane bean from the Swing containers and add it to the jPanelLeft bean Rename the new scroll pane to
jScrollPaneForCustomersList and change its gridy property from -1 to 1
To associate the scrollpane with the jListCustomers bean, you can add a line of code to the getJScrollPaneForCustomersList method:
jScrollPaneForCustomersList.setViewportView(getJListCustomers());
Even simpler: Select the jListCustomers bean in the Java Beans view and drop
it onto the scroll pane This makes the list a component of the scroll pane and adds the required line of code to the getJScrollPaneForCustomersList method: The complete code of the scroll pane is shown in Figure 14-35 If you click the jScrollPaneForCustomersList bean in the Java Beans view, the Visual Editor automatically navigates to this code in the Source view
Figure 14-35 Source code for the scroll pane
private javax.swing.JScrollPane getJScrollPaneForCustomersList() {
if(jScrollPaneForCustomersList == null) {
jScrollPaneForCustomersList = new javax.swing.JScrollPane();
jScrollPaneForCustomersList.setViewportView(getJListCustomers());
}
return jScrollPaneForCustomersList;
}
Trang 3Designing the right panel
Next, we want to add a JLabel bean to the jPanelRight and rename it to jLabelCustomerSelection We also change the text property from JLabel to
Customer Selection Once the JLabel has been added, we add a JTextField to the jPanelRight bean Also rename the JTextField from its initial value jTextField to jTextFieldCustomerSelection and change the gridy property from -1 to 1, to align the bean appropriate within this GridBagLayout panel
You also have to change the enabled property of the jTextFieldCustomerSelection from the initial value true to false By changing this property to false, we are not allowed to enter a value in the text field anymore
We also want to change the background color and the disabled text color properties of the text field By doing this, we demonstrate that we can also overwrite the default properties of a JavaBean by using the source editor
Add the following code statements to the initialize method:
getJTextFieldCustomerSelection().setBackground(getJPanelRight().getBackground()); getJTextFieldCustomerSelection().setDisabledTextColor(Color.black);
This statement will change the background color of the text field to the same as the jPanelRight panel uses as its background color To resolve the Color class, select Color and Source -> Organize Imports (context) Application Developer also adds automatically the following import statement to the class:
import java.awt.Color;
The last JavaBean we want to add to our sample GUI is the JButton Add the JButton bean to the jPanelRight, rename from jButton to jButtonGetFirstName and also set the text property to Get First Name The gridy property should also
be changed from -1 to 2
Improving the layout
As we have seen, all JavaBeans which have been placed on the GridBagLayout panels have constraint properties, except for the jLabelCustomerList bean that
is inside the scroll pane
To improve the layout of our sample GUI, we now change the insets property for all beans mentioned above Figure 14-36 shows the insets property of a
GridBagLayout component
Trang 4Change this property from its initial value 0,0,0,0 to 10,10,10,10 for all
JavaBeans in the two panels Changing this property specifies the external padding of the component and increases the space between the beans
Figure 14-36 Insets property of a GridBagLayout component
Now we have finished designing the sample GUI Figure 14-37 shows the Java Bean view of our sample GUI
Figure 14-37 Java Beans view of the sample GUI
Figure 14-38 shows the Design view of our sample GUI
This GUI is already runnable as a JavaBean However, it does not yet do anything but display The section “Running and testing JavaBeans” on page 504 provides a description of how to run and test a JavaBean
Trang 5Figure 14-38 Sample GUI in Design view
Adding data to the JavaBean
As shown in the section “Sample GUI” on page 470, we want to list the last names of the customers in the JList bean Chapter 5, “Developing Java applications” on page 93 uses a simple Java class (CustomerListing) that reads
a DB2 database table to retrieve information about Customers This sample code
is provided in Figure 5-10 on page 102
We want to reuse most of the code of this class in our ItsoProGuideGui project, modify some statements, and fill the jListCustomer bean with the last names of all records provided in the CUSTOMER table of the sample DB2 database
There are two ways to add the CustomerListing class to this project:
Create the class from scratch, place it in the itso.gui package, and add the code
Copy—if it exists—the class CustomerListing from the itso.java package of the ItsoProGuideJava project to the iso.gui package of this project and adapt the code
Figure 14-39 shows the sample class, where bold statements differ from the original Java class The code is provided in:
Note: This sample provides a simple guide showing how to create a small GUI
with some logic behind it For simplicity, this code does not follow any architectural practices or rules
Trang 6Figure 14-39 Sample class CustomerListing - adapted for sample GUI
package itso.gui;
import java.sql.*;
import java.util.Vector;
public class CustomerListing {
static String dbtab = "CUSTOMER";
public Vector getAllByLastName() {
Vector result = new Vector();
Connection con = null;
con = connect();
Statement stmt = null;
ResultSet rs = null;
String select = "SELECT * FROM ITSO." + dbtab;
try {
stmt = con.createStatement();
rs = stmt.executeQuery(select);
while (rs.next()) {
//String lastName = rs.getString("lastName");
result.addElement(rs.getString("lastName"));
}
//System.out.println("End of Listing");
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (SQLException e) {}
}
return result;
}
protected static Connection connect() {
Connection con = null;
try {
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
con = DriverManager.getConnection("jdbc:db2:EJBBANK");
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
}
return con;
}
}
Trang 7To add data to the JList bean of the sample GUI, we have to add some code to the initialize method The bold formatted code in Figure 14-40 shows the code which has to be added to the initialize method of the CustomerGUI class First we have to create an instance of the CustomerListing class which will be used to call the method getAllByLastName — which returns the last names of all customers of the CUSTOMER table — and stores the result in a Vector object, which
is named allCustomers The setListData method of the JList object adds the allCustomers vector to the list
Figure 14-40 Initialize method of the CustomerGUI class
If you would run the GUI now, then the last names of the customers would be displayed
Adding additional methods to the sample GUI
The sample GUI is not yet complete, as we have to implement some code which will enable the button and return the first name of the selected entry in the list
To do this, we first add a new method to the CustomerListing class This method
is called by a new method of the CustomerGUI class that has not been implemented yet
private void initialize() { java.awt.GridLayout layGridLayout1 = new java.awt.GridLayout();
layGridLayout1.setRows(1);
this.setLayout(layGridLayout1);
this.add(getJPanelLeft(), null);
this.add(getJPanelRight(), null);
this.setSize(330, 180);
getJTextFieldCustomerSelection().setBackground(getJPanelRight()
.getBackground());
getJTextFieldCustomerSelection().setDisabledTextColor(Color.black);
// initialize the list with data from the database CustomerListing customerList = new CustomerListing();
getJListCustomers().setListData(customerList.getAllByLastName());
}
Trang 8This method is similar to the getAllByLastName method (Figure 14-39 on page 499) You can copy and paste the getAllByLastName method and change the bold statements
Figure 14-41 getFirstNameByKey method of the CustomerListing class
Next we add a new method to the CustomerGUI class This method is called by the jButtonGetFirstName bean and returns the first name of the customer selected in the jListCustomers
Add the code as shown in Figure 14-42 to the class CustomerGUI
The method checks if an entry in the jListCustomers bean has been selected
If so, the method calls the getFirstNameByKey method, which returns the corresponding first name of the selected entry If nothing has been selected in the list, the method returns a string which says: No customer selected
public String getFirstNameByKey(String key) {
String result = new String();
Connection con = null;
con = connect();
Statement stmt = null;
ResultSet rs = null;
String select =
"SELECT * FROM ITSO." + dbtab + " WHERE lastName = '" + key + "'";
try {
stmt = con.createStatement();
rs = stmt.executeQuery(select);
while (rs.next()) {
result = rs.getString("firstName");
}
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (SQLException e) {}
}
return result;
}
Trang 9Figure 14-42 Method to retrieve the first name
Writing event handling code
Once we have added these methods to the CustomerListing and the CustomerGUI class, we add an action listener to the jButtonGetFirstName bean This is the last step to finish the sample GUI
We have to implement the action listener to trigger an action when the button in our GUI has been clicked
The Visual Composition Editor of Visual Age for Java allowed you to generate program logic by making connections between JavaBeans Visual Age for Java generated the appropriate code to attach the listener to the source JavaBean, and then executed the desired action on the target
The new Visual Editor in Application Developer does not implement the concept
of creating connections graphically between JavaBeans Such program logic is specified by writing code directly in the Java editor To help developers write the event handling code, Visual Editor provides several content assist templates Usually, each template has the same name as the method it is designed to work
private String getFirstName() {
String result = new String();
if (getJListCustomers().getSelectedIndex() == -1) { // Nothing has been selected in the list
result = "No customer selected.";
} else { // An item has been selected in the list String selectedItem =
getJListCustomers().getSelectedValue().toString(); CustomerListing customerList = new CustomerListing();
result = new String(customerList.getFirstNameByKey(selectedItem)); }
return result;
}
Note: An action listener is an event handler which has to be implemented to
respond to the user’s actions, such as clicking a push button
Trang 10To use the addActionListener template, navigate to the method that initialized the jButtonGetFirstName bean by selecting this bean in the Java Beans view The Visual Editor will select the appropriate method in the Source view
After you write the beginning of the line of code, for example,
jButtongetFirstName.addA, you can invoke code assist by pressing Ctrl-Space
on your keyboard The template will appear at the bottom of the content assist list, as shown in Figure 14-43
Figure 14-43 addActionListener template
The code skeleton as shown in Figure 14-44 is created automatically, after the addActionListener template has been added
Figure 14-44 Action listener code skeleton
Note: If the template for the event you wish to add is not present in the
available code assist list, then you might be able to import it into Application Developer The import file is named allTemplates.xml and is located in the Application Developer’s folder:
wstools\eclipse\plugins\com.ibm.etools.jbcf.codegen_5.0.1\Examples\
Templates\java\awt\event See “Code assist” on page 118 for more information regarding templates
jButtonGetFirstName.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) {
}
});