Title: Components
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Swing JComponents

BasicComponents.java

1. Swing contains an abstract class called JComponent. A lot of useful classes are derived from JComponent ( JButton, JTextField, JTextArea, etc). There is a lot of useful common software buried in the JComponent class.
2. You can also use the JComponent class as a basis for creating a GUI from more fundamental blocks. You can draw your own control and field your own keystrokes, mouse button clicks etc. We will do a little of this as well.
3. I would strongly recommend that you get familiar with navigating the java.awt and javax.swing packages, because we will only be scratching the surface of the capabilities.
4. Another key class to understand is the notion of a Container. A JFrame and and JApplet are both instances of a Container. A Container has all of the properties of JComponent in addition to the capability of being able to hold other JComponents inside of it. For example on your JFrame or your JApplet, you may want to add several buttons, textFields, etc. You can do this because the JApplet class has Container capabilities.
5. JTextField, and JTextArea - To have an online text field, use the JTextField class. If you want a multi-line input area, use the JTextArea class. Both of these classes are derived from JTextComponent. Keep this in mind, because if you don't find what you want in online help under JTextField, or JTextArea, you might want to consider looking under the JTextComponent class which has a lot of the basic functionality for both of these classes.
6. You may be wondering how you specify where on the screen these components show up. Java invented the concept of a Layout manager for determining where components show up on the screen. There are many different Layout manager options available and this is a major topic for later. For the time being don't worry where the JComponents show up. In fact, I have played some games with sizes of the container and sizes of the JComponents themselves to make it look not so bad.
7. In this example, we are also adding a JLabel class. A JLabel has no capability to receive user input. A JLabel merely holds onto static text.
8. Note that one of the problems with Applets is the fact that your Applet may be running in different versions of the JRE depending on what browser you are running.

BasicComponents.java



import java.awt.*;
import javax.swing.*;

public class BasicComponents extends JApplet {

    public void init() {
        // Construct a Label and add it with one command
        Container container = getContentPane();
        container.setLayout(new FlowLayout());
        container.add(new JLabel("This is a long label ........."));

        // Single Line Input/Output Field
        JTextField t = new JTextField(40);
        container.add(t);

        // Button
        JButton b = new JButton("Click here to get something done");
        container.add(b);

        // Multple Line Input/Output Field
        JTextArea toutput = new JTextArea(4,40);
        container.add(toutput);

        // Print out the Java Version you are using

         String javaVersion = System.getProperty("java.version");
        toutput.append(javaVersion);
     }

  public static void main(String[] args) {
    BasicComponents applet = new BasicComponents();
    JFrame aFrame = new JFrame("Basic Components");

    aFrame.getContentPane().add(applet);
    aFrame.setSize(600,250);
    // Normally the following call comes from the Browser
    applet.init();

    aFrame.setVisible(true);
  } // end of main
}




BasicAction.java

We have to jump ahead a little so we can get input back. We will talk about the Listener interfaces a lot more later, but for now we want to have some code that gets called everytime a button gets clicked. The way you do it is as follows:

1. You need a class that implements the ActionListener interface. We are going to take the easy approach here and claim that our BasicAction class implements ActionListener.
2. The ActionListener interface only has one routine in it, so we just add it to our BasicAction class:
public void actionPerformed(ActionEvent e)
3. Lastly, after we create our Button, we pass a pointer to a class that implements the ActionListener interface. In our program it happens to be the BasicAction class itself, so we just pass the keyword this. We do this by taking the Button instance b and issuing the command:
b.addActionListener(this);
4. In our actionPerformed routine we are going to fetch the text typed into the JTextField class (tinput) and append it to the end of our JTextArea class (toutput). To do this we used the setText and getText methods.
5. So you type input into either a JTextField or JTextArea. If you want to set either of these classes to have a certain string, use
setText(String text);
6. If you want to append text to the end of the buffer use:
append(String text);
7. getSelectedText() - this routine will return the selected text in a text component.
8. If you want to fetch the text currently in one of these classes use the routine:
String getText();
9. When using JTextArea, you need to explicitly enter in your newline (OS specific) string. So instead of using '\n' on Linux or '\r' '\n' on Windows, you can use System.getProperties to fetch the end of line separator.
10. Note that we have one System.out.println statement. This can be useful for debugging. If you are running from the command line or in the appletviewer, it is clear where this output is displayed. However, when this code is displayed in a real browser, you have to find the Java Console to see the output from your System.out.println. By the way sending a lot of output to the Java Console can slow things down considerably on the web --- the implementation is not efficient and should only be used for debug.

BasicAction.java



import java.awt.*;
import javax.swing.*;
import java.awt.event.*; // New Import for Events

public class BasicAction extends JApplet
    implements ActionListener
{
   JTextField tinput = new JTextField("TextField class", 60);
   JTextArea toutput = new JTextArea("TextArea class", 4, 60);
   String endline;

   public void init() {
        // Construct a Label and add it with one command
        Container container = getContentPane();

        container.setLayout(new FlowLayout());
        container.add(new JLabel("This is a long label ........."));

        container.add(tinput);

        JButton b = new JButton("Click here to get something done");
        container.add(b);
        container.add(toutput);

        b.addActionListener(this);
        endline= System.getProperty("line.separator");
     }

    public void actionPerformed(ActionEvent e) {
        String str = tinput.getText();

        toutput.append(str + endline);

        // Where does the following go???
        System.out.println(str);
       }


  public static void main(String[] args) {
    BasicAction applet = new BasicAction();
    JFrame aFrame = new JFrame("Basic Action");

    aFrame.getContentPane().add(applet);
    aFrame.setSize(600,250);
    // Normally the following call comes from the Browser
    applet.init();

    aFrame.setVisible(true);
  } // end of main
}






Consider adding the following code at the end of the init routine:

Wit the following code, we are setting our container (JApplet in this case) to have a background color of yellow and a Foreground color of red. In theory, JComponents that are added to a container should default to these properties. You can also explicitly set these properties by calling setBackground and setForeground for each JComponent. Make these changes and run it in different environments (I.E., Netscape, appletviewer, and the Command Line. See if the theory holds up.


        b.setBackground(Color.cyan);
        toutput.setBackground(Color.magenta);
        toutput.setForeground(Color.blue);


BasicAction.java with colorations

There are many other methods available in the JComponent class that are available to all classes derived from JComponent. As others are encountered, I will try to point them out.

So far we have looked at the JLabel class, JButton, JTextField and JTextArea classes. In this section, we are going to look at classes that are related to making choices.

JCheckbox

1. A JCheckbox has a name and a state (true or false). If the state is true, the Checkbox has a check in it.
// Create a named Checkbox with a default state of false
JCheckbox(String name); // Constructor
2. If you want to read back the state of the Checkbox,
call the isSelected() method.
3. If you want to change the state of the Checkbox,
call setSelected(boolean newstate).

Radio Boxes

1. The JRadioButton class implements a radio button.
JRadioButton(String name); // Name on the Radio button
2. To keep track of all of the Radio buttons that go in a group, we need the class:
ButtonGroup();
3. To add a radio button to a ButtonGroup, you call the add method with the JRadioButton instance.
buttonGroup.add(rbutton);
4. To set one of the Radio buttons in the ButtonGroup set, call the method
setSelected(boolean value);
Note that setting one of the buttons to true implies setting all of the other radio buttons in the ButtonGroup to false.
5. To find out if a radio button is set, call the method:
isSelected().

Swing Selection JComponents

Check.java

Check.java


import java.awt.*;
import javax.swing.*;
import java.awt.event.*; // New Import for Events

public class Check extends JApplet
    implements ActionListener
{
   JTextArea toutput = new JTextArea(6,40);

   // Regular Check Boxes
   JCheckBox chkCar = new JCheckBox("Own Car?");
   JCheckBox chkStudent = new JCheckBox("Student at WCC?");

   // Radio Button Classes
   ButtonGroup generation = new ButtonGroup();
   JRadioButton[] genChk= new JRadioButton[5];

   String endline;
   String genName[] = {"Senior", "Boomer", "X", "Adolescent", "Infant"};

   public void init() {
        // Default the following checkbox to checked
        chkStudent.setSelected(true);
        Container container = getContentPane();
        container.setLayout(new FlowLayout());
        container.add(chkCar);
        container.add(chkStudent);
        //chkCar.addActionListener(this);
        //chkStudent.addActionListener(this);
        container.add(new Label("**********************Checkbox**Radio*****************************"));

        for (int i=0; i < genName.length; i++)
        {
            genChk[i] = new JRadioButton(genName[i]);
            //genChk[i].addActionListener(this);

            generation.add(genChk[i]);
            container.add(genChk[i]);
        }
        // Set default radio button selection
        genChk[2].setSelected(true); // Set generation X by default



        container.add(new Label("*****************************************************************"));
        JButton b = new JButton(
            "--         Click here to get something done       --");
        container.add(b);
        container.add(toutput);

        b.addActionListener(this);
        endline= System.getProperty("line.separator");
     }

    public void actionPerformed(ActionEvent evt) {
        String str;
        int[] indexes;
        String[] strs;

       toutput.append("****" + evt.getActionCommand() + endline);
        toutput.append("Student at WCC? " +
            chkStudent.isSelected()  + endline);
        toutput.append("Own Car? " +
            chkCar.isSelected()  + endline);

        for (int i=0; i < genChk.length; i++)
            if (genChk[i].isSelected())
            {
                toutput.append("generation: " + genName[i] + endline);
                // Could put a break here and get the same answer
            }

       }


  public static void main(String[] args) {
    Check applet = new Check();
    JFrame aFrame = new JFrame("Check");

    aFrame.add(applet);
    aFrame.setSize(380,380);
    // Normally the following call comes from the Browser
    applet.init();

    aFrame.setVisible(true);
  } // end of main
}



Selection.java

I haven't figured out the Swing version of the following AWT applet. So ... I have left the code and description according to the AWT version.

There are also 2 useful classes that give you selection lists.

1. The Choice class gives you a Drop-Down Selection box
2. The List class gives you a list of selections that you can make. There is a method you can call to allow the List box to allow multiple selections:
setMultipleMode(true);
3. The methods available for both the Choice and the List are:
  - add(String name) - add a new entry to the list
  - remove(String name) - remove an entry. This throws an exception if the entry doesn't exist.
  - getItemCount( ) - return number of entries in the list
  - String getSelectedItem( ) - return the currently selected item
  - int getSelectedIndex( ) - return the currently selected index
4. If your List has the MultipleMode flag set, then you can also call
  - int[] getSelectedIndexes( )- return an array of selected indexes
  - String[] getSelectedItems( ) - return an array of selected entries

Selection.java


import java.awt.*;
import java.awt.event.*; // New Import for Events

public class Selection extends java.applet.Applet
    implements ActionListener
{
   TextArea toutput = new TextArea(4,40);
   TextField tadd = new TextField(40);

   // Dropdown Selection Box
   Choice myChoice = new Choice();

   // Selection List allowing only one selection
   List myList = new List();

   // Selection List allowing multiple selections
   List myMultList = new List();

   String endline;
   String strlist[] ={"zero", "one", "two", "three", "four", "five"};

   public void init() {
        add(new Label("**********************Choice**************************************"));
        add (myChoice);
        for (int i = 0; i < strlist.length; i++)
            myChoice.add(strlist[i]);

        add(new Label("**********************List****************************************"));
        add (myList);
        for (int i = 0; i < strlist.length; i++)
            myList.add(strlist[i]);

        add(new Label("**********************List**Multiple Selection********************"));
        add (myMultList);
        // Make this list allow multiple selections
        myMultList.setMultipleMode(true);
        for (int i = 0; i < strlist.length; i++)
            myMultList.add(strlist[i]);

        add(new Label("********String to add to lists (- in front will remove)***********"));
        add(tadd);
        Button b = new Button(
            "--         Click here to get something done       --");
        add(b);
        add(toutput);

        b.addActionListener(this);
        endline= System.getProperty("line.separator");
     }

    public void actionPerformed(ActionEvent evt) {
        String str;
        int[] indexes;
        String[] strs;

        toutput.append("**********************************" + endline);
        toutput.append("myChoice: total: "   + myChoice.getItemCount() + endline+
                        "      selected index = " + myChoice.getSelectedIndex() +
                        " selected item = "  + myChoice.getSelectedItem() + endline);

        toutput.append("myList: total: "   + myList.getItemCount() + endline+
                        "      selected index = " + myList.getSelectedIndex() +
                        " selected item = "  + myList.getSelectedItem() + endline);

        indexes = myMultList.getSelectedIndexes();
        strs = myMultList.getSelectedItems();
        toutput.append("myMultList: "+ endline);
        for (int i = 0; i < indexes.length; i++)
        {
           toutput.append("   index = " + indexes[i] +
                          " item = " + strs[i] + endline);
        }

        str = tadd.getText();
        str = str.trim();

        // If any string is found in the tadd TextField, we will either try
        // to add a string to the choice, list and multiple list components
        // or remove a string.  Removing happens if the string starts with a "-"

        if (str.length() > 0)
        {
            if (str.charAt(0) != '-')
                {
                    myChoice.add(str);
                    myList.add(str);
                    myMultList.add(str);
                    toutput.append("Successfully added " + str +
                        " to lists " + endline);

                }
             else
                {
                    // Remove from lists
                    try
                    {
                        str = str.substring(1); // remove - sign
                        myChoice.remove(str);
                        myList.remove(str);
                        myMultList.remove(str);
                        toutput.append("Successfully removed " + str +
                            " from lists " + endline);
                    }
                    catch (IllegalArgumentException e)
                    {
                        toutput.append("Exception: " + e + endline);
                    }

                }
        }
       }


  public static void main(String[] args) {
    Selection applet = new Selection();
    Frame aFrame = new Frame("Selection");

    aFrame.add(applet);
    aFrame.setSize(380,480);
    // Normally the following call comes from the Browser
    applet.init();

    aFrame.setVisible(true);
  } // end of main
}




Exercises:

Job Applicaton Form

Create a job application form applet that utilizes most of the JComponents we have covered so far. When you click an Apply button, the results of the application form should be written to System.out.println. Your applet should demonstrate at least the following JComponents:

1. Textfield
2. TextArea
3. Checkbox
4. Radio Buttons
5. Label
6. Button

You can put any fields you want in your application, but here are some recommendations:

You could have the following textfields:
Name, address, Social Security number

For a List box, you might have your applicant pick from a list of skills that you provide. For example,
C++, Java, Html, MFC, Visual Basic, Oracle, etc.

For a choice box, you might have a list of states. You might only want to put in a few of the local states. I.e.:
Michigan, Indiana, Ohio, Wisconsin, Illinois

For a Checkbox (non-radio type), you could choose something like:
Married, Veteran, Own Car

For a radio button you could choose,
Sex: Male/Female , Eye Color: Blue/Brown/Green/Other

Use the Label JComponent to properly label the input fields of your application.

Create the user interface to an ATM machine

Create the user interface to a vending machine

Calculator Example

Create a Command Line Form Based Calculator Program and an Applet Program. These 2 programs should be almost the same, but not identical --- in otherwords, I want only Applet code in the Applet and only Form related code in the Command Line Program.

Your programs should at least implement the first 2 items in the following list. The last 2 items are for an extra challenge.
- Your programs provide simple calculator functionality. Your program should have the name Calculator. You only need to handle 10 digit buttons (0,1, ... 9), the "+" button, the "=" button a clear button and a text field for the result. Don't worry about the button layouts for now. We will deal with that later.
- Add additional buttons for multiply and divide. Don't let a user divide by zero and blow up your calculator
- Add additional buttons for sin, cos, tan. You can find out about these functions in the language Math class. You might want to have radio buttons to select between degrees or radians for the input angle.

HINT: See CalcFlow.java in the Layout section for the start of a calculator program.

Last Updated: April 6, 2008 8:20 PM