GUIs AND COMPONENTS (TEXT FIELDS AND AREA, SCROLLING LISTS AND DROP DOWN MENUES)

CONTENTS

1. Introduction
2. Text fields
3. Text fields Swing Example
4. Text areas
6. Text areas Swing Example
7. Scrolling lists
8. Drop down menues


1. INTRODUCTION

In a previous www page l illustrate the use of labels, checkboxes and radiobuttons; in this page I will illustrate the use of text fields and areas, scrolling lists and drop down menues.



2. TEXT FIELDS

Text fields are components into which we can write text or display text. In the first case we normally wish to "collect" the text and do something with it. Some sample code is given in Table 1. Here we decalred three instances of the class TextField as private data memebers of the class gui. We do this so that the identifiers can be accessed frim anywhere within the class (and not just within a method as in previous examples). In the constructor for the user defined class Gui, which extends the class Frame, we setv the background colour, adopt the "flow layout" layout manager and add a window listner so that we can close the window when desired.

We then cal; the TextField constructor three times, once for each desired instance of the TextField class. In all three cases we specify the number of characters as 45. In the second case we also specify a initial text string which is to appear in the field (Figure 1). We then declare some labels and add them to the frame. For each text field we add an action listener so that we can do something with the entered text.

The listner, on detecteing a carriage return, automatically calls the actionPerformed method. The text is placed in a local data item data using the getActionCommand method. Alternatively, since the class TextField inherits frim the class TextComponent, the instance method getText from this class may be used:

String data1 = name.getText();
String data2 = address.getText();
String data3 = telephone.getText();

However this does mean reading every text field after which we still have to determine which one has actually been changed. Instead, in the example code, we determine which field has been changee using the getSource method which rerturns the name of the relevant text field instance.

In most cases we wish to be able to edit text fields, but sometimes it is desirable to switch editting of. We do this using the setEditable method whose single argument must be a boolean value. This is illustrated in the code presented in Table 1.

The presented code also gives an illustration of how to output text to a text field using the method setText.

// GUI Example 1 
// Frans Coenen
// 31 July 2001
// Revised Thursday 13 March 2003
// Dept. of Comp. Sci., University of Liverpool

import java.awt.*;
import java.awt.event.*;

public class TextFieldExample1 extends Frame implements WindowListener, ActionListener {


    // ------------------------------ FIELDS --------------------------------
    
    private TextField name = new TextField(45);
    private TextField address = new TextField("My address",45);
    private TextField telephone = new TextField(45);
    private int nameEditFlag=0;
    
    Label nameLab = new Label("     Name");
    Label addLab  = new Label("  Address");
    Label telLab  = new Label("Telephone");
   
    // ---------------------------- CONSTRUCTORS ----------------------------
    
    public Gui(String text) {
        super(text);
	setBackground(Color.pink);
	setLayout(new FlowLayout());
	addWindowListener(this);
	
	// Text fields
	
	add(nameLab);
	add(name);
	name.addActionListener(this);
	add(addLab);
	add(address);
	address.addActionListener(this);
	add(telLab);
	add(telephone);
	telephone.addActionListener(this);		
	}
   
    /* ------------------------------------------------- */
    /*                                                   */
    /*                      METHODS                      */ 
    /*                                                   */
    /* ------------------------------------------------- */
        
    /* ACTION PERFORMED */
   
    /* Process textfield events */
                         
    public void actionPerformed(ActionEvent event) {
                       
        String data = event.getActionCommand();
	if (event.getSource() == name) {
	    if (nameEditFlag==0) {
	        System.out.println("NAME: " + data);
	        name.setText(data + " (CONFIRMED)");
	        name.setEditable(false);
		nameEditFlag=1;
		}
	    }	
	else {
	    if (event.getSource() == address) 
	    		System.out.println("ADDRESS: " + data);
            else System.out.println("TELEPHONE: " + data);
	    }
	}
	
    /* Window Closed */
    
    public void windowClosed(WindowEvent event) {
        }

    /* Window Deiconified */
    
    public void windowDeiconified(WindowEvent event) {
        }

    /* Window  Iconified */
    
    public void windowIconified(WindowEvent event) {
        }

    /* Window Activated */
    
    public void windowActivated(WindowEvent event) {
        }

    /* Window Deactivated */
    
    public void windowDeactivated(WindowEvent event) {
        }

    /* Window Opened */
    
    public void windowOpened(WindowEvent event) {
        }

    /* Window Closing */
    
    public void windowClosing(WindowEvent event) {
        System.exit(0);
	} 
    }

/* -------------------------------------------------- */
/*                                                    */
/*                  APPLICATION CLASS                 */
/*                                                    */
/* -------------------------------------------------- */    
  
class TextFieldExample1App {
    
    /* Main  method */    
    
    public static void main(String[] args) {
        TextFieldExample1 screen = new TextFieldExample1("GUI Example 1");
        
        screen.setSize(500,160);
        screen.setVisible(true);
        }
    }

Table 1:Constructor that creates 3 text field components

GUI TEXT FIELDS

Figure 1: Result of exacuting code presented in Table 1.



3. TEXT FIELDS SWING EXAMPLE

The example presented in Table 2 is similar to that presented in Table 1 but uses Javax Swing components including the password field. Output is achieved using the showMessageDialog method from the JOptionPane Swing class.

// Text Field Example 2 
// Frans Coenen
// Thursday 13 March 2003
// Dept. of Comp. Sci., University of Liverpool
// Based on Example given in Deitel and Deitel (2003)

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

public class TextFieldExample2 extends JFrame implements ActionListener {
    
    /* ------------------------------------------------- */
    /*                                                   */
    /*                      FIELDS                       */ 
    /*                                                   */
    /* ------------------------------------------------- */
	    	
    private JTextField textField1, textField2, textField3;
    private JPasswordField passwordField;
    
    /* ------------------------------------------------- */
    /*                                                   */
    /*                   CONSTRUCTORS                    */ 
    /*                                                   */
    /* ------------------------------------------------- */
    
    /* Creates four text fields: (1) text field with default size, (2)
    yext field with default text, (3) uneditable text field, (3) password
    text filed. */
    
    //GuiTextFieldExamples.setLayout() use 
    //GuiTextFieldExamples.getContentPane().setLayout() instead

    public TextFieldExample2(String text) {
        super(text);
	Container container = getContentPane();
	container.setLayout(new FlowLayout());
	
	// construct textfield with default sizing
	textField1 = new JTextField(10);
	container.add(textField1);
	
	// construct textfield with default text
	textField2 = new JTextField("Enter text here");
	container.add(textField2);
	
	// construct textfield with default text
	// 20 visible elements and no event handler
	textField3 = new JTextField("Uneditable text field",20);
	textField3.setEditable(false);
	container.add(textField3);
	
	// Construct password field with default text
	passwordField = new JPasswordField("Hidden text");
	container.add(passwordField);
	
	// register event handlers
	textField1.addActionListener(this);
	textField2.addActionListener(this);
	textField3.addActionListener(this);
        passwordField.addActionListener(this);
        
	setSize(325,100);
        setVisible(true);
	}
   
    /* ------------------------------------------------- */
    /*                                                   */
    /*                      METHODS                      */ 
    /*                                                   */
    /* ------------------------------------------------- */
        
    /* ACTION PERFORMED */
    
    /* Process textfield events */
   
    public void actionPerformed(ActionEvent event) {
	String textString = "";
	    
	// User pressed Enter in JTextField textField1
	if (event.getSource() == textField1)
	    	textString = "textField1: " + event.getActionCommand();
	    
	// User pressed Enter in JTextField textField2
	else if (event.getSource() == textField2)
	    	textString = "textField2: " + event.getActionCommand();
	
	// User pressed Enter in JTextField textField3
	else if (event.getSource() == textField3)
	    	textString = "textField3: " + event.getActionCommand();
		
	// User pressed Enter in JTextField passwordField
	else if (event.getSource() == passwordField) 
	    	textString = "passwordField: " + 
			new String(passwordField.getPassword());
	        	
	JOptionPane.showMessageDialog(null,textString);
	}
    }
    
/* -------------------------------------------------- */
/*                                                    */
/*                  APPLICATION CLASS                 */
/*                                                    */
/* -------------------------------------------------- */    
  
class TextFieldExample2App {

    /* Main  method */    
    
    public static void main(String[] args) {
        TextFieldExample2 screen = 
			new TextFieldExample2("GUI TExt Field");
        screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    }

Table 2:Constructor that creates 3 text field components and a "password" text field.



4. TEXT AREAS

A text area allows for the input/output of larger amounts of text than is practicable using text fields. We specify a text area using one of the TextArea constructors from the TextArea class. In the example in table 2 we have used the 4 argument constructor (the last argument can have the values SCROLLBARS_BOTH, SCROLLBARS_ORIZONTAL_ONLY, SCROLLBARS_NONE and SCROLLBARS_VERTICAL_ONLY). The code sample given in Table 3 also includes a text listener defined in the TextListener interface which automatically invokes the method textValueChanged when triggered.

// Text Area Example 1 
// Frans Coenen
// Thursday 13 March 2003
// Dept. of Comp. Sci., University of Liverpool

import java.awt.*;
import java.awt.event.*;

class TextAreaExample1 extends Frame implements WindowListener, TextListener {
    
    /* ------------------------------------------------- */
    /*                                                   */
    /*                       FIELDS                      */ 
    /*                                                   */
    /* ------------------------------------------------- */  
    
    private TextArea cDescribe;
    
    /* ------------------------------------------------- */
    /*                                                   */
    /*                   CONSTRUCTORS                    */ 
    /*                                                   */
    /* ------------------------------------------------- */
    
    public TextAreaExample1(String text) {
        super(text);
        setBackground(Color.lightGray);
        setLayout(new FlowLayout());
        addWindowListener(this);
        String cText = "C++ is essentially an object-oriented extension to C. It was\n" +
        "developed by Stroustrup in the early 1980s. The first commercial\n" +
        "version was introduced in 1985. The language uses the SIMULA class\n" +
        "construct to provide for data abstraction and information hiding, and\n" +
        "also supports class inheritance. Various changes have been made to the\n" +
        "language since its inception. Current versions have the ANSI Standard C\n" +
        "as a subset. Consequently programs written in ANSI C can be compiled on\n"+
        "C++ compilers. A further feature of C++ (over C) is that the type\n" +
        "checking is much stricter.\n";
        
        // Text fields
        
        cDescribe = new TextArea(cText,5,45,TextArea.SCROLLBARS_BOTH);
        
        add(cDescribe);
        cDescribe.addTextListener(this);        
        }
                     
    /* ------------------------------------------------- */
    /*                                                   */
    /*                       METHODS                     */ 
    /*                                                   */
    /* ------------------------------------------------- */

    /* Text value changed */
                 
    public void textValueChanged(TextEvent event) {
               
        String data = cDescribe.getText();
        if (event.getSource() == cDescribe) System.out.println(data);
        }   
    	    
    /* WINDOW EVENT HANDLERS */
     	   
    /* Window Closing */    
    public void windowClosing(WindowEvent event) {
        System.exit(0);
        } 
    /* Window Closed */ 
    public void windowClosed(WindowEvent event) {}
    /* Window Deiconified */   
    public void windowDeiconified(WindowEvent event) {}
    /* Window  Iconified */    
    public void windowIconified(WindowEvent event) {}
    /* Window Activated */   
    public void windowActivated(WindowEvent event) {}
    /* Window Deactivated */   
    public void windowDeactivated(WindowEvent event) {}
    /* Window Opened */    
    public void windowOpened(WindowEvent event) {}
    }
   
/* -------------------------------------------------- */
/*                                                    */
/*                  APPLICATION CLASS                 */
/*                                                    */
/* -------------------------------------------------- */        
    
class TextAreaExample1App {
    
    /* Main  method */    
    
    public static void main(String[] args) {
        TextAreaExample1 screen = new TextAreaExample1("Text Area Example 1");
        
        screen.setSize(500,160);
        screen.setVisible(true);
        }
    }	

Table 3: Text area example

GUI CHECK BOXES

Figure 2: Result of exacuting code presented in Table 3.



5. TEXT AREAS SWING EXAMPLE

The code in Table 4 is a Java Swing version of that presented in the previous Section.

// Text Area Example 2 
// Frans Coenen
// Thursday 13 March 2003
// Dept. of Comp. Sci., University of Liverpool

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

class TextAreaExample2 extends JFrame {
    
    /* ------------------------------------------------- */
    /*                                                   */
    /*                       FIELDS                      */ 
    /*                                                   */
    /* ------------------------------------------------- */  
    
    private JTextArea cDescribe;
    
    /* ------------------------------------------------- */
    /*                                                   */
    /*                   CONSTRUCTORS                    */ 
    /*                                                   */
    /* ------------------------------------------------- */
    
    public TextAreaExample2(String text) {
        super(text);
        setBackground(Color.lightGray);
        Container container = getContentPane();
	container.setLayout(new FlowLayout());
        
        String cText = "C++ is essentially an object-oriented extension to C. It was\n" +
        "developed by Stroustrup in the early 1980s. The first commercial\n" +
        "version was introduced in 1985. The language uses the SIMULA class\n" +
        "construct to provide for data abstraction and information hiding, and\n" +
        "also supports class inheritance. Various changes have been made to the\n" +
        "language since its inception. Current versions have the ANSI Standard C\n" +
        "as a subset. Consequently programs written in ANSI C can be compiled on\n"+
        "C++ compilers. A further feature of C++ (over C) is that the type\n" +
        "checking is much stricter.\n";
        
        // Text fields
        
        cDescribe = new JTextArea(cText,5,30);
        
        container.add(new JScrollPane(cDescribe));   
        }
                     
    /* ------------------------------------------------- */
    /*                                                   */
    /*                       METHODS                     */ 
    /*                                                   */
    /* ------------------------------------------------- */

    /* NONE */
                 
    }
   
/* -------------------------------------------------- */
/*                                                    */
/*                  APPLICATION CLASS                 */
/*                                                    */
/* -------------------------------------------------- */        
    
class TextAreaExample2App {
    
    /* Main  method */    
    
    public static void main(String[] args) {
        TextAreaExample2 screen = new TextAreaExample2("Text Area Example 2");
        screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        screen.setSize(500,160);
        screen.setVisible(true);
        }
    }

Table 4: Text area Swing example



6. SCROLLING LISTS

A scrolling list component is created by first creating a list component using the List constructor (as shown in Table 5), and then adding the list element into the list component using the add method. Thus we are adding components (list elements) to a component (a list) of a component (a frame).

A scrolling list has two types of listener, activated by either a single click or a double click. The first is an action listener which calls the actionPerformed method. The second is an item listener which calls the actionPerformed method and the itemStateChanged method.

class Gui extends Frame implements WindowListener, ActionListener, 
			ItemListener {

   /* Constructor */
    
    public Gui(String text) {
        super(text);
	setBackground(Color.orange);
	setLayout(new FlowLayout());
	addWindowListener(this);
	
	List menu = new List(4,true);
	
	// List items
	
	menu.add("Ada");
	menu.add("Algol");
	menu.add("Basic");
	menu.add("C");
	menu.add("Cobol");
	menu.add("Fortran");
	menu.add("Modula");
	menu.add("Pascal");
	menu.add("Simula");
	
	add(menu);
	menu.addActionListener(this);
	menu.addItemListener(this);	
	}
	
    /* Action performed */
                         
    public void actionPerformed(ActionEvent event) {
    	String nameOfItem = event.getActionCommand();
	System.out.println(nameOfItem);
	}

    /* Item state changed */
    
    public void itemStateChanged(ItemEvent event) {
    	switch(((Integer) event.getItem()).intValue()) {
	    case 0:
		System.out.println("Ada");
		break;
	    case 1:
	        System.out.println("Algol");
		break;
	    case 2:
	        System.out.println("Basic");
		break;
	    case 3:
	        System.out.println("C");
		break;
	    case 4:
	        System.out.println("Cobol");
		break;
	    case 5:
	        System.out.println("Fortran");
		break;
	    case 6:
	        System.out.println("Modula");
		break;
	    case 7:
	        System.out.println("Pascal");;
		break;
	    case 8:
	        System.out.println("Simula");
		break;
	    default:
	        System.out.println("ERROR");
	    }
        }

And so on		

Table 5: Scrolling lists example

GUI SCROLLING LIST

Figure 3: Result of exacuting code presented in Table 5.



7. DROP DOWN MENUES

To create a drop down menu we first create an instance of the class MenuBar, and then create however many menues we wish to add to this bar (2 in the example given in Table 6). Note that elements for each menu are added in the same way that we added elements to a scrolling list. We use an action listener to determine which item has been selected.

// Button Example 1 
// Frans Coenen
// 31 July 2001
// Revised Thursday 13 March 2003
// Dept. of Comp. Sci., University of Liverpool

import java.awt.*;
import java.awt.event.*;

public class MenuExample1 extends Frame implements WindowListener, ActionListener {
    
    /* ------------------------------------------------- */
    /*                                                   */
    /*                       FIELDS                      */ 
    /*                                                   */
    /* ------------------------------------------------- */  
        
    MenuBar bar = new MenuBar();
    Menu lang = new Menu("LANGUAGES");
    Menu para = new Menu("PARADIGM");
    
    /* ------------------------------------------------- */
    /*                                                   */
    /*                   CONSTRUCTORS                    */ 
    /*                                                   */
    /* ------------------------------------------------- */
    
    public MenuExample1(String text) {
        super(text);
        
	setBackground(Color.magenta);
        setLayout(new FlowLayout());
        addWindowListener(this);
               
        // Create lang menu
        lang.add("Ada");
	lang.add("C++");
        lang.add("java");
	lang.add("pascal");
        lang.add("prolog");
        lang.add("Miranda");
        
        // Create paradigm menu
        para.add("Imperative");
        para.add("Object oriented");
        para.add("Logic");
        para.add("Functional");
        
        // Add items to bar
        bar.add(lang);
        bar.add(para);
        this.setMenuBar(bar);
        
        // Add event listeners        
        lang.addActionListener(this);
        para.addActionListener(this);               
        }
                     
    /* ------------------------------------------------- */
    /*                                                   */
    /*                       METHODS                     */ 
    /*                                                   */
    /* ------------------------------------------------- */
        
    /* ACTION PERFORMED */
    
    /* Process textfield events */
                             
    public void actionPerformed(ActionEvent event) {
	    
        // User selected from pradigm menu
        if (event.getSource() == lang) {
            String nameOfItem = event.getActionCommand();
	    System.out.println(nameOfItem);
            }
        // User selected from language menu
	else if (event.getSource() == para) {             
            String nameOfItem = event.getActionCommand();
	    System.out.println(nameOfItem);
	    }
        }
    
    /* WINDOW EVENT HANDLERS */
     	   
    /* Window Closing */    
    public void windowClosing(WindowEvent event) {
        System.exit(0);
        } 
    /* Window Closed */ 
    public void windowClosed(WindowEvent event) {}
    /* Window Deiconified */   
    public void windowDeiconified(WindowEvent event) {}
    /* Window  Iconified */    
    public void windowIconified(WindowEvent event) {}
    /* Window Activated */   
    public void windowActivated(WindowEvent event) {}
    /* Window Deactivated */   
    public void windowDeactivated(WindowEvent event) {}
    /* Window Opened */    
    public void windowOpened(WindowEvent event) {}
    }
   
/* -------------------------------------------------- */
/*                                                    */
/*                  APPLICATION CLASS                 */
/*                                                    */
/* -------------------------------------------------- */            
    
class MenuExample1App {
    
    /* Main  method */    
    
    public static void main(String[] args) {
        MenuExample1 screen = new MenuExample1("Menu example1 1");
        
        screen.setSize(500,100);
        screen.setVisible(true);
        }
    }

Table 6: Drop down menu example

MENU

Figure 4: Result of exacuting code presented in Table 6.




Created and maintained by Frans Coenen. Last updated 20 March 2003