Using Swing Components

   

Java™ 2 Primer Plus
By Steven Haines, Steve Potts

Table of Contents
Chapter 16.  The Swing Library


Swing contains another set of graphical objects called components. Components are normally thought of as objects that you place inside of containers. You have been introduced to two types of components in the listings dealing with containers: buttons and text fields. Examples of common components include the following classes:

  • JTextField

  • JButton

  • JLabel

  • JCheckBox

  • JChoice List

  • JList

  • JMenu Components

All these classes extend the javax.swing.JComponent class. This class provides a number of methods that are useful to all the graphical components. The methods setLocation(), setForground(), setBackground(), addMouseListener(), and so on, come from this base class.

The JtextField Component

A JTextField is a component that contains a single line of text for data entry. It can vary in length, but it can't extend for more than one line. The JTextField class, javax.swing.JTextField, provides the following important methods:

  • addActionListener() The listener class is one that receives notification when an action event occurs.

  • setColumns() Sets the number of columns.

  • setText() Sets or modifies the text.

  • removeActionListener() Removes an action listener.

  • getListeners() Returns an array of all listeners that are associated with this object.

The first example that we will work simply places a JTextField object on a JFrame. Listing 16.7 shows the code for the application.

Listing 16.7 The TestJTextField.java File
 /*   * TestJTextFields.java   *   * Created on July 30, 2002, 11:35 AM   */  package ch16;  import javax.swing.*;  import java.awt.*;  import java.awt.event.*;  /**   *   * @author  Stephen Potts   * @version   */  public class TestJTextFields extends JFrame  {      JTextField tfield1;      JTextField tfield2;      /** Creates new TestJTextField */      public TestJTextFields()      {          tfield1 = new JTextField(15);          tfield2 = new JTextField(20);          tfield2.setText("Some Sample Text");          tfield2.setFont(new Font("Courier",Font.BOLD,16));          tfield2.setEditable(false);          tfield2.select(12,15);          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);          JPanel p1 = new JPanel();          p1.add(tfield1);          p1.add(tfield2);          getContentPane().add(p1);          setTitle("Using JTextFields");          setBounds( 100, 100, 300, 300);          setVisible(true);       }      public static void main(String[] args)      {          TestJTextFields tp = new TestJTextFields();      }  } 

We instantiate the text fields with a length to display.

 tfield1 = new JTextField(15);  tfield2 = new JTextField(20); 

We populate the second field with some text and change its font.

 tfield2.setText("Some Sample Text");  tfield2.setFont(new Font("Courier",Font.BOLD,16)); 

We also make it noneditable. The object tfield2 is left empty and editable.

 tfield2.setEditable(false); 

Running this example displays the result shown in Figure 16.7 (after you type a few characters in the first field).

Figure 16.7. JTextFields can be manipulated manually and programmatically.

graphics/16fig07.gif

The color of the second text field was changed automatically to indicate that it is not editable.

Adding Buttons

One of the most popular graphical components is the button. The button class, javax.swing.JButton, provides the following important methods:

  • addActionListener() Receives notification when the button is clicked.

  • setLabel() Sets the label text for the button.

  • removeActionListener() Removes the association between this button and the listener class.

Adding a button to a container is a fairly simple process. Listing 16.8 shows how we would add a button to an application.

Listing 16.8 The TestJButton.java File
 /*   * TestJButton.java   *   * Created on July 30, 2002, 2:36 PM   */  package ch16;  import java.awt.*;  import javax.swing.*;  import java.awt.event.*;  /**   *   * @author  Stephen Potts   * @version   */  public class TestJButton extends JFrame implements ActionListener  {     JButton btnExit;     /** Creates new TestJButton */     public TestJButton()     {        btnExit = new JButton("Exit");        btnExit.setFont(new Font("Courier", Font.BOLD, 24));        btnExit.setBackground(Color.cyan);        Cursor curs = new Cursor(Cursor.HAND_CURSOR);        btnExit.setCursor(curs);        btnExit.addActionListener(this);        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        getContentPane().add(btnExit);        this.getContentPane().setLayout(new FlowLayout());        setTitle("Using a JButton and an ActionListener");        setBounds( 100, 100, 300, 300);        setVisible(true);     }     public void actionPerformed(ActionEvent ae)     {        if (ae.getActionCommand().equals("Exit"))           System.exit(0);     }     public static void main(String[] args)     {        TestJButton td = new TestJButton();     }  } 

We create a button and put a label on it.

 btnExit = new JButton("Exit"); 

We also set the font to be different from the default.

 btnExit.setFont(new Font("Courier", Font.BOLD, 24)); 

We change the color of the button.

 btnExit.setBackground(Color.cyan); 

The Cursor class controls the shape of the cursor when the mouse is over this object. We change it from the default arrow to the hand-shaped cursor called HAND_CURSOR.

 Cursor curs = new Cursor(Cursor.HAND_CURSOR); 

The setCursor() command takes a Cursor as a parameter.

 btnExit.setCursor(curs); 

The connection between the Button that will contain the actionPerformed() method is made here. The word this means that the class that we are writing code for will provide this method.

 btnExit.addActionListener(this); 

The actionPerformed() method is called whenever the button is clicked.

 public void actionPerformed(ActionEvent ae)  { 

The getActionCommand() method returns the value of the label that was given to it when it was instantiated. This is one way to determine which button in a class was clicked. Here there is only one button in the application, and it displays the string Exit. All that it does when this is clicked is terminate the application.

    if (ae.getActionCommand().equals("Exit"))        System.exit(0);  } 

The result from running this example is shown in Figure 16.8.

Figure 16.8. A JButton's appearance can be modified using method calls.

graphics/16fig08.gif

Notice the color of the background is a cyan (blue), the font is larger and bolded, and the cursor changes to a hand shape when you move the mouse over the button. The cursor changes back when the cursor leaves the button area.

JTextArea

A JTextArea object is a rectangular text field that can be longer than one line, and it can be set to read-only. A JTextArea can have zero, one, or two scrollbars, which makes it useful for long pieces of text. There are several methods that can be used to set or modify the text in a JTextArea.

  • append Adds a String to the end of the text.

  • insert Adds the String at position x in the TextArea and shifts the rest of the text to the right.

  • replaceRange Replaces the text between a start and an end point with a String that gets passed in.

We see these methods in action in Listing 16.9.

Listing 16.9 The TestJTextArea.java File
 /*   * TestJTextArea.java   *   * Created on July 30, 2002, 2:36 PM   */  package ch16;  import javax.swing.*;  import java.awt.*;  import java.awt.event.*;  /**   *   * @author  Stephen Potts   * @version   */  public class TestJTextArea extends JFrame implements ActionListener  {      JButton btnExit;      JButton btnAppend;      JButton btnInsert;      JButton btnReplace;       JTextArea taLetter;      JPanel p1;      JScrollPane sp;      /** Creates new TestJTextArea */       public TestJTextArea()      {          btnAppend = new JButton("Append");          btnAppend.addActionListener(this);          btnInsert = new JButton("Insert");          btnInsert.addActionListener(this);          btnReplace = new JButton("Replace");          btnReplace.addActionListener(this);          btnExit = new JButton("Exit");          btnExit.addActionListener(this);          taLetter =          new JTextArea(10,20);          taLetter.setLineWrap(true);          taLetter.setWrapStyleWord(true);          taLetter.append(                "I am writing this letter to inform you that you");          taLetter.append(                " have been drafted into the United States Army.");          taLetter.append(                " You will report to Fort Bragg, North Carolina ");          taLetter.append(                "on July 20, 1966.  You will be assigned to ");          taLetter.append("Vietnam.");          p1 = new JPanel();          p1.add(taLetter);          //create the scroll pane          sp = new JScrollPane(p1);          sp.setHorizontalScrollBarPolicy(                     JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);          sp.setVerticalScrollBarPolicy(                     JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);          getContentPane().add(btnAppend);          getContentPane().add(btnInsert);          getContentPane().add(btnReplace);          getContentPane().add(btnExit);          getContentPane().add(sp);           this.getContentPane().setLayout(new FlowLayout());          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);          setTitle("Using a JTextArea Object");          setBounds( 100, 100, 400, 400);          setVisible(true);      }      public void actionPerformed(ActionEvent ae)      {          if (ae.getActionCommand().equals("Append"))               taLetter.append("\n\nSincerely, \n     The Draft Board");          if (ae.getActionCommand().equals("Insert"))              taLetter.insert("Dear Steve,\n     ", 0);          if (ae.getActionCommand().equals("Replace"))              taLetter.replaceRange("Dear Jerry,\n     ", 0, 12);          if (ae.getActionCommand().equals("Exit"))              System.exit(0);      }      public static void main(String[] args)       {          TestJTextArea tjta = new TestJTextArea();      }  } 

The JTextArea object is created with the number of rows and columns specified.

 taLetter =  new JTextArea(10,20); 

By default, the JTextArea class does not wrap. We need to specify that we want wrapping, and that we want to break only on word boundaries.

 taLetter.setLineWrap(true);  taLetter.setWrapStyleWord(true); 

The append() method adds text to the letter.

 taLetter.append(        "I am writing this letter to inform you that you");  taLetter.append(        " have been drafted into the United States Army.");  taLetter.append(        " You will report to Fort Bragg, North Carolina ");  taLetter.append(        "on July 20, 1966.  You will be assigned to ");  taLetter.append("Vietnam."); 

No scrollbars are associated with the JTextArea object. Swing provides the JScrollPane and the JPanel objects to provide the scrollbars.

 p1 = new JPanel();  p1.add(taLetter);  //create the scroll pane  sp = new JScrollPane(p1);  sp.setHorizontalScrollBarPolicy(             JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  sp.setVerticalScrollBarPolicy(             JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); 

We append the JScrollPane object to the JFrame along with the buttons.

 getContentPane().add(btnAppend);  getContentPane().add(btnInsert);  getContentPane().add(btnReplace);  getContentPane().add(btnExit);  getContentPane().add(sp); 

The event handler calls different JTextArea methods to append, insert, and replace text.

 public void actionPerformed(ActionEvent ae)  {      if (ae.getActionCommand().equals("Append"))          taLetter.append("\n\nSincerely, \n     The Draft Board");      if (ae.getActionCommand().equals("Insert"))          taLetter.insert("Dear Steve,\n     ", 0);      if (ae.getActionCommand().equals("Replace"))          taLetter.replaceRange("Dear Jerry,\n     ", 0, 12);      if (ae.getActionCommand().equals("Exit"))          System.exit(0);  } 

The result of running this example is shown in Figure 16.9.

Figure 16.9. Buttons can be used to trigger method calls on the JTextArea object.

graphics/16fig09.gif

Note how the \n causes new lines to be inserted in the text. You can use this technique to perform some crude formatting.

JCheckBox

A JCheckBox is a switch that can either be checked as on or off. JCheckboxes are useful as toggle switches and for representing choices of on/off or yes/no.

The listener class that handles events generated by check boxes is the ItemListener interface. This interface requires that the itemStateChanged() method be implemented. The JVM will call this method for you whenever an item changes that has a listener registered for it. Listing 16.10 shows how this works.

Listing 16.10 The TestJCheckBoxes.java File
 /*   * TestJCheckboxes.java   *   * Created on July 30, 2002, 2:36 PM   */  package ch16;  import javax.swing.*;  import java.awt.*;  import java.awt.event.*;  /**   *   * @author  Stephen Potts   * @version   */  public class TestJCheckBoxes extends JFrame implements ItemListener  {     JCheckBox cbWhiteBread;     JCheckBox cbWheatBread;     JCheckBox cbRyeBread;     JCheckBox cbToasted;      JTextField tField;     /** Creates new TestJCheckBoxes*/     public TestJCheckBoxes()     {        cbWhiteBread = new JCheckBox("White Bread");        cbWhiteBread.addItemListener(this);        cbWheatBread = new JCheckBox("Wheat Bread");        cbWheatBread.addItemListener(this);        cbRyeBread = new JCheckBox("Rye Bread");        cbRyeBread.addItemListener(this);        cbToasted= new JCheckBox("Toasted");        cbToasted.addItemListener(this);        tField = new JTextField(20);         getContentPane().setLayout(new FlowLayout());        getContentPane().add(cbWhiteBread);        getContentPane().add(cbWheatBread);        getContentPane().add(cbRyeBread);        getContentPane().add(cbToasted);        getContentPane().add(tField);         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        setTitle("Using JCheckBoxes");        setBounds( 100, 100, 300, 300);        setVisible(true);     }     public void itemStateChanged(ItemEvent ie)     {        JCheckBox cb = (JCheckBox)ie.getItemSelectable();        if( cb.isSelected())           tField.setText(cb.getText());        else           tField.setText("Not " + cb.getText());     }     public static void main(String[] args)     {        TestJCheckBoxes tcb = new TestJCheckBoxes();     }  } 

The constructor for the JCheckBox object takes a string that becomes the text associated with the check box.

 cbWhiteBread = new JCheckBox("White Bread"); 

This class is its own ItemListener.

 cbWhiteBread.addItemListener(this); 

We need a JTextField object to display the event results.

 tField = new JTextField(20); 

We add the objects to the JFrame.

 getContentPane().add(cbWhiteBread);  getContentPane().add(cbWheatBread);  getContentPane().add(cbRyeBread);  getContentPane().add(cbToasted);  getContentPane().add(tField); 

The event handler is implemented in this class.

 public void itemStateChanged(ItemEvent ie)  { 

The getItemSelectable() method tells us which check box caused the event to fire.

 JCheckBox cb = (JCheckBox)ie.getItemSelectable(); 

The isSelected() method tells you whether the box was checked or unchecked.

    if( cb.isSelected())        tField.setText(cb.getText());     else        tField.setText("Not " + cb.getText());  } 

The result of running this example is shown in Figure 16.11.

Figure 16.10. JCheckBoxes are useful for values that are either true or false and on or off.

graphics/16fig10.gif

Figure 16.11. ButtonGroup objects are used to create mutually exclusive JRadioButtons.

graphics/16fig11.gif

Notice that multiple bread types can be checked at the same time, even though these choices are logically exclusive. In the following section, you will learn how to constrain the user to only one choice.

JRadioButton

The JRadioButton class enables you to limit the number of boxes that the user can select to one at the time. Checking another will automatically uncheck the first. Listing 16.11 shows a modified version of Listing 16.10 that uses JRadioButtons instead of JCheckBoxes.

Listing 16.11 The TestJRadioButtons.java File
 /*   * TestJRadioButtons.java   *   * Created on July 30, 2002, 2:36 PM   */  package ch16;  import javax.swing.*;  import java.awt.*;  import java.awt.event.*;  /**   *    * @author  Stephen Potts   * @version   */  public class TestJRadioButtons extends JFrame implements ItemListener  {     JRadioButton rbWhiteBread;     JRadioButton rbWheatBread;     JRadioButton rbRyeBread;     JRadioButton rbToasted;     ButtonGroup bg;      JTextField tField;     /** Creates new TestJRadioButtons*/     public TestJRadioButtons()     {        rbWhiteBread = new JRadioButton("White Bread");        rbWhiteBread.addItemListener(this);        rbWheatBread = new JRadioButton("Wheat Bread");        rbWheatBread.addItemListener(this);        rbRyeBread = new JRadioButton("Rye Bread");        rbRyeBread.addItemListener(this);        rbToasted= new JRadioButton("Toasted");        rbToasted.addItemListener(this);        tField = new JTextField(20);        bg = new ButtonGroup();        bg.add(rbWhiteBread);        bg.add(rbWheatBread);         bg.add(rbRyeBread);        getContentPane().setLayout(new FlowLayout());        getContentPane().add(rbWhiteBread);        getContentPane().add(rbWheatBread);        getContentPane().add(rbRyeBread);        getContentPane().add(rbToasted);        getContentPane().add(tField);        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        setTitle("Using TestJRadioButtons");        setBounds( 100, 100, 300, 300);        setVisible(true);     }      public void itemStateChanged(ItemEvent ie)     {        JRadioButton rb = (JRadioButton)ie.getItemSelectable();        tField.setText(rb.getText());     }     public static void main(String[] args)      {        TestJRadioButtons trb = new TestJRadioButtons();     }  } 

The result of running this example is shown in Figure 16.11.

Notice the round appearance of the RadioButtons that were added to the group.

JList

A JList object is a list of elements that the user can choose from. It normally allows more than one item to be displayed at a time, and it can allow for more than one item to be selected at the same time. Listing 16.12 shows an example of this.

Listing 16.12 The TextJLists.java File
 /*   * TestJLists.java   *   * Created on July 30, 2002, 2:36 PM   */  package ch16;   import javax.swing.*;  import javax.swing.event.*;  import java.awt.*;  import java.awt.event.*;  /**   *   * @author  Stephen Potts   * @version   */  public class TestJLists extends JFrame implements ListSelectionListener  {      JList lstBread;      JTextField tField;       /** Creates new TestJLists*/      public TestJLists()      {          String[] names = {"White Bread", "Wheat Bread", "Rye Bread"};          lstBread = new JList(names);          lstBread.addListSelectionListener(this);          tField = new JTextField(" ",20);          getContentPane().setLayout(new FlowLayout());          getContentPane().add(lstBread);          getContentPane().add(tField);          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);          setTitle("Using JLists");          setBounds( 100, 100, 300, 300);          setVisible(true);      }      public void valueChanged(ListSelectionEvent lse)       {          String selection = "";          if (lse.getValueIsAdjusting())          {              return;          }          int[] selected = lstBread.getSelectedIndices();          for(int i=0; i < selected.length; ++i)          {              selection = selection + " " +                 (String) lstBread.getModel().getElementAt(selected[i]);              tField.setText(selection);           }      }      public static void main(String[] args)      {          TestJLists tc = new TestJLists();      }  } 

This example uses a swing event, so we must import the javax.swing.event package.

 import javax.swing.event.*; 

The ListSelectionListener interface is defined in this package.

 public class TestJLists extends JFrame implements ListSelectionListener 

The easiest way to populate the JList model is using an array of Strings.

 String[] names = {"White Bread", "Wheat Bread", "Rye Bread"};  lstBread = new JList(names); 

We add the listener in the usual way.

 lstBread.addListSelectionListener(this); 

The ListSelectionListener requires that we implement the valueChanged() method.

 public void valueChanged(ListSelectionEvent lse)  {      String selection = ""; 

The getValueIsAdjusting() method reports on the event when the mouse is pressed. We simply return when this happens.

 if (lse.getValueIsAdjusting())  {      return;  } 

We get an array of the selected indexes so that we can display all the selections.

 int[] selected = lstBread.getSelectedIndices(); 

We append the item to the end of the tField string on each pass.

 for(int i=0; i < selected.length; ++i)  {      selection = selection + " " +         (String) lstBread.getModel().getElementAt(selected[i]);      tField.setText(selection);  } 

Notice that we had to cast the results to the String type. The result of running this is shown in Figure 16.12.

Figure 16.12. JList objects are useful when you want to allow users to choose more than one item from a list.

graphics/16fig12.gif

Notice that you are able to choose multiple items in the list by pressing the <ctrl> key.


       
    Top
     



    Java 2 Primer Plus
    Java 2 Primer Plus
    ISBN: 0672324156
    EAN: 2147483647
    Year: 2001
    Pages: 332

    Similar book on Amazon

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net