CSC 161 Lab 3-1 JTextField and JLabel

Introduction to Text Fields

Text fields allow users to type small amounts of text into a program. For example, the address bar at the top of your browser where you type in addresses like http://wwww.thingone.com is a text field. We want to learn how to use text fields in our programs.

Here is the skinny on Java text fields. They are created from the javax.swing.JTextField class. This class has two constructors

JTextField()
JTextField(int columns)

which respectively create a text field, and a text field that is big enough to hold a string of characters whose length is specified by the columns parameter. This is an approximate length depending on the average width of a character in the font being used by the JTextField.

Using Text fields

Here are other methods implemented by JTextField. We list them here, and then we will discuss them how to use them afterwards.

void addActionListener(ActionListener l)
void setActionCommand(String command)
String getText()
boolean isEditable()
void setEditable(boolean b)

JTextField objects fire an ActionEvent whenever the user types text in them and then hits the ENTER key. The easiest way to use a text field is to attach an ActionListener to the JextField using its addActionListener() method. You can use setActionCommand() to set a string that will be sent with the the ActionEvent to help identify which this text field as the source of the ActionEvent. In the handler for the ActionEvent, you will typically use getSource() on the ActionEvent to retrieve a reference to the text field. Then, you can use getText() to retrieve the string typed by the user.

There can be times when you do not want the user to enter text into a text field. For example, if a text field is for entering the name of a spouse, and the user is currently enjoying the state of singlehood, then the spouse text field is not applicable and should not be editable. That is what the last two methods are for.

Try it Out: Our first JTextField

We want to write a program that displays a single text field, as shown on the left.

When the user types their name and hits ENTER, the program displays a personalized JOptionPane that greets the user by name, as shown on the right.

Here is a partially completed program that does this. It creates a frame, puts a text field in the frame, adds a listener to the text field, and adds the text field to the frame. The listener is invoked when the user hits ENTER in the text field. When invoked, the listener retrieved the reference to the text filed, gets the text in the text field, and uses that text in a JOptionPane.

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

public class Main
{
    public static void main(String[] args)
    {
       // Create a specialized JFrame: its constructor
       // does everything.
       new MyFrame();
    }
}

class MyFrame extends JFrame
{
   public MyFrame()
    {
       // Set title by invoking superclass constructor
       super("Fun With Text Fields");
       this.setLayout(new FlowLayout());
       // Create a JTextField and add an actionListener to it
       JTextField nameTextField = new JTextField(15);
       nameTextField.addActionListener(new NameListener());
       // Add text field to frame
       this.add(nameTextField);

       // Do usual stuff to make the frame usable
       this.pack();
       this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       this.setVisible(true);
   }
}

// This class implements the ActionListener for the Text Field.
// The action listener will display a JOptionPane with the string
// "Hello " just before the text typed into the text field.
class NameListener 
{
   
}

Challenge: Apply the knowledge you have gained to fill in the missing code in the NameListener class and make the program work.

Challenge: Try and figure out how to make the JOptionPane display on top of the JTextField in the frame. Hint: Find out what the first parameter in showMessageDialog, which we set to null, is for.

Labels

A text field is great for getting a single line of input from a user. When you want to display small amounts of information to the user, you use a JLabel. Here are JLabel methods.

JLabel()
JLabel(String text)
JLabel(String text, int alignment)
void setText(String text)
String getText()
void setHorizontalAlignment(int alignment)

I will let you figure out on your own what these methods do. The alignment parameter must be one of SwingConstants.CENTER, SwingConstants.LEFT, or SwingConstants.RIGHT.

A program with Labels

Start a new project, called MoreFunWithTextFields. In this program, we will use both text fields and labels. The intent is to create a frame that shows a text field and a label, with the label begin above the text field. When you run the program it should appear as on the right. You can start with the code below.


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

public class Main
{
    public static void main(String[] args)
    {
       // Create a specialized JFrame: its constructor
       // does everything.
       new MyFrame();
    }
}

class MyFrame extends JFrame
{
   public MyFrame()
    {
       // Set title by invoking superclass constructor
       super("More Fun With Text Fields");

       JTextField nameTextField = new JTextField(20);
       JLabel greetingLabel = new JLabel("This is a label");

       // Add nameTextField to North of BorderLayout of frame


       // Add greetingLabel to South of BorderLayout of frame



       // Do usual stuff to make the frame usable
       this.pack();
       this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       this.setVisible(true);
   }
}

Greeting program using a label

Now, we want to have the program greet the user as before, but this time, instead of using a JOptionPane the program will display the greeting in the JLabel. To do, this you will write a separate class, TextLabelListener, that responds to ActionEvent on the text field and writes a greeting on the label. Consider the following points.

Challenge: Write the TextLabelListener class, and complete the program so that when the user typed their name in the text field, an personal greeting appears on the label below the text field.

Project 2: Modify the program to get rid of the JLabel and put a a subclass of JPanel in its place. Modify the frame so that it sets its size to 400x100 instead of using pack().

Create your subclass of JPanel so that it has a void setText(String text) method. It will need to store the string passed to setText. Then, override its paintComponent method, so that it uses drawString to write the string it is storing. You may center the string in the panel, but this is not required.

Now modify your program so that you get rid of the label and use your subclass of JPanel in its place. Add your panel to the center part of the {\tt JFrame} to avoid having the panel be squeezed to where you can't see it.

Project 2 is due Monday of Week 4, at midnight.