New to Java

New to Java Programming Center

New to Java

Programming Center

Java Platform Overview | Getting Started | Learning Paths
References & Resources | Certification | Supplements




 

Read the API for class JComboBox. Which line of code is correct to make the combo box editable?

The proper way to set a combo box to editable is by calling the setEditable method:

week.setEditable(true);

 

More on Swing Components

Lesson: Using Swing Components

Creating a GUI with JFC/Swing

Building GUIs with JFC/Swing APIs Code Samples

 

Identifiers for GUI Components

JComboBox is just one of a few GUI features you're going to use in this UIWestPanel class, so you must import javax.swing and java.awt packages. The GUI components include some functionality, such as popping up a message, so you also need to implement the ActionListener and ItemListener interfaces.

Next, set up the variables needed for the components. This pane consists of JLabels and JTextFields. Declare variables for each of these.

 


  1. Create a file called UIWestPanel.java in your text editor.
  2. Add the following imports:
    package divelog;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    
  3. Add the following class declaration:
    public class UIWestPanel extends JPanel 
                     implements ActionListener, ItemListener
      { //Opens class
    
  4. Declare the following variables:
         private JLabel diveNumber = 
                       new JLabel("Dive #: ");
         private JLabel diveNumberL = 
                       new JLabel();
         private JLabel menu2 = 
                       new JLabel("Maximum Depth");
         private JLabel jelly = 
                new JLabel("", 
                  new ImageIcon("images/jellyfish.jpg"), 
                                         JLabel.CENTER);     
         private JLabel dateL = 
                   new JLabel("Date: " );
         private JTextField date = 
                  new JTextField("00/00/00");                                     
         private JComboBox maxDepths = 
                       new JComboBox(depths);
         private JLabel psiStartL = 
                    new JLabel("PSI Start:");
         private JTextField psiStart = 
                     new JTextField("0000");
         private JLabel psiEndL = 
                     new JLabel("PSI End:");
         private JTextField psiEnd = 
                      new JTextField("000");
         private JLabel psiUsedL = 
                    new JLabel("PSI Used:");
         private JLabel psiUsed = 
                         new JLabel();
         private JLabel bottomTimeL = 
              new JLabel("Time in Minutes:");
         private JTextField bottomTime = 
                        new JTextField("00");
         private JLabel visL = 
                   new JLabel("Visibility:");
         private JTextField vis = 
                       new JTextField("000");
         private JLabel location = 
                    new JLabel("Dive Type: "); 
                        
         private JRadioButton rb;
         private JRadioButton boatButton; 
         private JRadioButton shoreButton; 
         
         // To hold result for ButtonGroup
         private JRadioButton b;
         private JLabel blank = new JLabel(" ");
         protected JButton view;
         protected JButton enter;
         private int count = 0;
         
         //String for JComboBox result
         private String s;
    
  5. Save the file. Your UIWestPanel.java file should look like this example.

Next, begin the class constructor by setting the layout for this pane to BorderLayout, and setting the background color to white.

 


  1. Open the UIWestPanel.java in your text editor.
  2. Start the class constructor
    public UIWestPanel ()
     { // Open constructor
    
      } // Closes constructor
    
  3. Add the set methods for background and layout as shown in bold:
     public UIWestPanel ()
      { // Open constructor  
                                 setLayout(new BorderLayout());        setBackground(Color.white);   
      } // Closes constructor
     
                        
  4. Save the file.

Now you're ready to work with the individual components for this pane. (You've created text fields for input in previous parts of the Building an Application series, so those are not covered in detail here.) Often applications need components that offer suggested input responses from users. One way of creating such components is to give the user a drop-down menu with a list of items to select, or radio buttons in which to select an item. To create these features, you use the JComboBox and JRadioButton classes.

Combo Boxes

Created with the JComboBox class, a combo box is an object with an editable area (if you desire) and a drop-down list of selectable items. Instances of JComboBox are not editable by default, but can be set to editable with the setEditable method.

To create a JComboBox, call one of the following constructors:

  • JComboBox(): Creates a default combo box.
  • JComboBox(ComboBoxModel aModel): Creates a combo box that takes its items from an existing ComboBoxModel.
  • JComboBox(Object[] items): Creates a combo box that contains the elements in the specified array.
  • JComboBox(Vector items): Creates a combo box that contains the elements in the specified Vector.

The UIWestPanel class calls the JComboBox constructor and supplies a String array to create the list of items.

An array is an object or data structure that holds multiple elements of the same type. Arrays are frequently used in applications that need a grouping of data assigned to one variable. In this case, you'll use the String array to hold the various dive depths the user can choose from the drop-down menu.

You define arrays in several ways. For the combo box you're creating, the easiest technique is to populate the array with the strings to display in the drop-down menu. The following example is an array of strings with the days of the week.

String days[] = {"Sunday", "Monday", "Tuesday", 
   "Wednesday",  "Thursday", "Friday", "Saturday"};
    
// This array is populated with seven String objects. 
// Because they are strings, they must be enclosed in 
// quotes. 

Once the array is defined, pass it to the JComboBox constructor:

JComboBox week;
String days[] = {"Sunday", "Monday", "Tuesday", 
   "Wednesday",  "Thursday", "Friday", "Saturday"};
week = new JComboBox(days);

After initializing a combo box with an array to provide items for the drop-down menu, you can set how many of those items display in the list at once. If there are more than the specified number, scroll bars appear for the user to view other items on the list. To set maximum rows, call the setMaximumRowCount method and provide an int for the number of items to display:

week.setMaximumRowCount(5);


More GUI Components for User Input

A JComboBox object uses a ListCellRenderer object to determine how the elements are displayed. In addition, it also uses a ComboBoxModel object to provide methods to access the combo box elements.

When the user explicitly makes a selection, the JComboBox fires an ActionEvent, and the actionPerformed method defines what should happen as a result of this selection.

Another method you'll use is getSelectedItem, which is later called in the actionPerformed method. The getSelectedItem method returns the currently selected item.

 


  1. Open the UIWestPanel.java in your text editor.
  2.  

  3. Add the following String array definition, shown in bold, to the constructor:
    public UIWestPanel ()
     { // Open constructor
      setLayout(new BorderLayout());
      setBackground(Color.white);
      // Define string array for the combo box.
       
                           String[] depths = { "1", "10", "20", "30", "40",                "50","60", "70", "80", "90", "100", "120",                             "140", "160 ", "180", "200" }; 
                        
  4. Pass the array reference to the JComboBox constructor:
                            maxDepths = new JComboBox(depths);   } // Closes constructor
                        
  5. Set the maximum row count to 5, set the background to white, and set the setEditable method for the combo box to true:
      // Define string array for combo box.
      String[] depths = { "1", "10", "20", 
            "30", "40", "50","60", "70", "80", "90", 
                  "100", "120", "140", "160 ", "180", 
                                             "200" }; 
     maxDepths = new JComboBox(depths);
      
                           maxDepths.setMaximumRowCount(5);  maxDepths.setBackground(Color.white);  maxDepths.setEditable(true);
                        
  6. Register the component with an ActionListener, shown in bold:
     maxDepths.setBackground(Color.white);
     maxDepths.addActionListener(this);
     maxDepths.setEditable(true);
      
                           maxDepths.addActionListener(this);
      } // Closes constructor  
                        
  7. Save the file.


Note that you can change the number of rows to display (more or less) through the setMaximumRowCount method, if you prefer. In addition, this menu is editable so that the user can change 50 feet to 52, or whatever increment is needed for a particular dive.

Radio Buttons

Radio buttons appear as small round button icons by default, and can have associated text. They are created in a group so that only one button at a time can be selected. When a button is selected, any other that had been selected is now deselected.

 

Use one of the following JRadioButton constructors to create radio buttons, depending on your needs:

 

  • JRadioButton()
    Creates an initially unselected radio button with no set text.
  • JRadioButton(Icon icon)
    Creates an initially unselected radio button with the specified image but no text.
  • JRadioButton(Icon icon, boolean selected)
    Creates a radio button with the specified image and selection state, but no text.
  • JRadioButton(String text, Icon icon)
    Creates a radio button that has the specified text and image, and that is initially unselected.
  • JRadioButton(String text, Icon icon, boolean selected)
    Creates a radio button that has the specified text, image, and selection state.

In addition to creating buttons, you must also add them to a button group; otherwise, more than one button can be selected.

Follow these five steps to create a group of radio buttons:

  1. Create buttons from the JRadioButton class:
    JRadioButton b1 = new JRadioButton("Shark");
    JRadioButton b2 = new JRadioButton("Tuna"); 
    JRadioButton b3 = new JRadioButton("Dolphin");
    
  2. Register the buttons with ItemListener:
    b1.addItemListener(this);
    b2.addItemListener(this);
    b3.addItemListener(this);
    
  3. Create a ButtonGroup object:
    ButtonGroup bg = new ButtonGroup();
    
  4. Add the buttons to the button group:
    bg.add(b1);
    bg.add(b3);
    bg.add(b3);
    
  5. Add the radio buttons to the panel:
    JPanel p = new JPanel();
    p.add(b1);
    p.add(b2);
    p.add(b3);
    

When a radio button is selected, an ItemEvent is generated and the itemStateChanged method is called. Within this method, you provide the code for what you want to happen when a radio button is selected. In the case of the Log Dives pane, you want to know which button was selected by getting the name of the button. To get the originator of an event, call the getItemSelectable method.

 


  1. Open the UIWestPanel.java in your text editor.
  2.  

  3. Call JRadioButtons constructors, supplying strings for accompanying text, as shown below in bold:
    maxDepths.setEditable(true);
                            boatButton = new JRadioButton("Boat"); shoreButton = new JRadioButton("Shore"); shoreButton.setBackground(Color.white); boatButton.setBackground(Color.white);
                        
  4. Register the component with an ItemListener:
    //Adding listeners for functionality
                            shoreButton.addItemListener(this); boatButton.addItemListener(this); 
                        
  5. Create a button group for these two radio buttons, and add the buttons to the group:
                            ButtonGroup group = new ButtonGroup(); group.add(boatButton); group.add(shoreButton);
                        
  6. Save the file.


 

Completing the Constructor

Next, create two buttons: one for the panel that allows a user to save dive information, and another to read saved dive data. For now these buttons are generic. Later, you'll assign text and functionality for these buttons in a different class. Recall that UIWestPanel concentrates on GUI components, not the functionality.

Once you've created the labels, buttons, and radio buttons you need, create a panel to add them to and add the panel to the pane itself. This completes the constructor for the UIWestPanel class.

 


  1. Open the UIWestPanel.java in your text editor.
  2.  

  3. Initialize two generic JButtons as shown below in bold:
    ButtonGroup group = new ButtonGroup();
    group.add(boatButton);
    group.add(shoreButton);
                            view = new JButton(); enter = new JButton();
                        
  4. Create a panel and add the components you've created:
                            //Create panel for components JPanel wpanel = new JPanel(new GridLayout(14, 2, 0, 0)); wpanel.setBackground(Color.white); //Add components        //Combo Box for depth of dive wpanel.add (menu2); wpanel.add (maxDepths); wpanel.add(dateL); wpanel.add(date); wpanel.add(location); wpanel.add(blank); wpanel.add(shoreButton); wpanel.add(boatButton); wpanel.add(Box.createVerticalStrut(3)); wpanel.add(Box.createVerticalStrut(3)); wpanel.add(psiStartL); wpanel.add(psiStart); wpanel.add(psiEndL); wpanel.add(psiEnd); wpanel.add(psiUsedL); wpanel.add(psiUsed); wpanel.add(bottomTimeL); wpanel.add(bottomTime); wpanel.add(visL); wpanel.add(vis); wpanel.add(diveNumber); wpanel.add(diveNumberL); wpanel.add(enter); wpanel.add(view);
                        
  5. Save the file.


Because the UIWestPanel class builds the GUI features, copy the code for the text area and shark image to a panel and into this constructor. The panel with these objects can then be added to the East area of the pane.


  1. Open UIWestPanel.java in your text editor.
  2. Add the code for the text area and shark image to this constructor:
    //Define textarea, and create panel
    //for textarea, shark, and button
    JPanel cpanel = new JPanel();
    comments = new JTextArea(15, 10);
    comments.setLineWrap(true);
    comments.setWrapStyleWord(true);     
    scrollpane = new JScrollPane(comments);
    scrollpane.setVerticalScrollBarPolicy(
         JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    whiteshark = new JLabel("", 
               new ImageIcon("images/gwhite.gif"), 
                                    JLabel.CENTER);
    box = Box.createVerticalBox();
    box.add(scrollpane);
    box.add(Box.createVerticalStrut(35));
    box.add(whiteshark);
    cpanel.setBackground(Color.white);
    cpanel.add(box);
    
  3. Add the panels to the pane:
    //Add panels to border layout of 
    // Dives object.
    add(jelly, "North");
    add(cpanel, "East");
    add(wpanel, "West");     
     } // Closes constructor
    </ol>
    </td></tr></table>
           
                           
    
    The graphical components for this interface are now complete. When the  
                           UIWestPanel class constructor is called from another class, the GUI is built and ready for input. A few of these components have some functionality you'll implement in this class, but the main functionality of the buttons goes into the controlling class that you'll create later.
    
    <h3>Implementing Promised Methods</h3>
                           
    
    
    The  
                           UIWestPanel class constructor is complete, but the class itself is not. Recall that this class implements the  
                           ActionListener and  
                           ItemListener interfaces, which means you must implement specific methods in this class. In these methods, you'll provide a few instructions for what you want to happen when the graphical component is used.
    
                           
    
    <center><table>
    <tr><td>
    <table>
    <tr><td>
    Which methods do you have to implement?
    </td></tr>
    <td>
    <form>
                           
       A.  </td>
    <td>
    <pre>
    public void getSize(int size)
    public void getComponent(Component c)
                        
   B.  
public void actionPerformed(ActionEvent ae)
public void itemStateChanged(ItemEvent ie)
   C.   All of the above