Module 3: String Input
An example with the Face applet
First, what do we mean by input?
- There are many applets you can write that require no input
from the user. These applets draw, paint or write stuff.
- However, applets that take in user input and process them to
produce results are more interesting and powerful.
- Here, we will look at the most elementary of such inputs:
a string in a textfield.
Consider this example:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class FaceWithGreeting extends Applet implements ActionListener {
// A String variable to hold the name when it has been entered.
String name;
// The text field in which the user enters a string.
TextField inputField;
// This method is automatically called for initialization.
// This is where we build parts of the applet: buttons, textfields etc.
public void init ()
{
//-----------------------------------------------------------
// Ignore the code between the dashed lines for now.
setLayout (new BorderLayout());
Panel bottomPanel = new Panel ();
Label nameLabel = new Label ("Enter your name: ");
bottomPanel.add (nameLabel);
inputField = new TextField (15);
bottomPanel.add (inputField);
Button nameEnteredButton = new Button ("Press when done");
bottomPanel.add (nameEnteredButton);
nameEnteredButton.addActionListener (this);
add (bottomPanel, BorderLayout.SOUTH);
//-----------------------------------------------------------
// Initially the string that's in the name variable should be
// blank because that's what we'll print before a name is entered.
name = "";
}
// The method actionPerformed is called when the button is clicked.
public void actionPerformed (ActionEvent click)
{
// Retrieve the string, if any, that was typed into the textfield:
name = inputField.getText ();
// Redraw the applet. This is necessary because it's inside the paint
// method that we depict the string.
repaint ();
}
public void paint (Graphics g)
{
// The Face, as before:
g.drawOval (40,40, 120,150); // Head
g.drawOval (57,75, 30,20); // Left eye
g.drawOval (110,75, 30,20); // Right eye
g.fillOval (68,81, 10,10); // pupil (left)
g.fillOval (121,81, 10,10); // pupil (right)
g.drawOval (85,100, 30,30); // Nose
g.fillArc (60,125,80,40, 180,180); // Mouth
g.drawOval (25,92, 15,30); // Left ear
g.drawOval (160,92, 15,30); // Right ear
// The greeting:
g.drawOval (160,125, 150,40); // An oval for the greeting.
String greeting = "Hello " + name; // Combine these two strings into one.
g.drawString (greeting, 190,150); // Draw the greeting
}
}
Note:
- The applet allows the user to enter a string into a textfield,
push a button and see a response.
- For now, let's ignore the parts of the program that build the
GUI components (such as the textfield, the button etc).
- Java calls the actionPerformed method when the button
is clicked;
- In here is where we place code to handle button-click events.
- In this case, we retrieve the string that was typed into
the textfield by the user and redraw the applet.
- Why redraw? This is how we ask Java to call our
paint method in which we actually draw stuff.
- In paint, we draw a greeting that consists of the
string "Hello" and the name joined as one string:
- Note that you use the + operator to concatenate
(join) two strings:
String greeting = "Hello " + name; // Combine these two strings into one.
- A new string, stored in the variable greeting, is
the result.
- Thus, if the name field was "Bob", the variable
greeting will contain the string "Hello Bob".
- Link to applet
Variables
What's a variable?
- The program above contained a few variables. For our purposes,
the most important ones were name and greeting.
- A variable is an identifier we create to store values for later use.
- You can define variables to hold strings, numbers, characters or objects.
Let's look at the program again, this time focusing mainly on the
two variables name and greeting:
// ... left out the import's for illustration ...
public class FaceWithGreeting extends Applet implements ActionListener {
// A String variable to hold the name when it has been entered.
String name;
public void init ()
{
//-----------------------------------------------------------
// ... left this out for illustration ...
//-----------------------------------------------------------
// Initially the string that's in the name variable should be
// blank because that's what we'll print before a name is entered.
name = "";
}
// The method actionPerformed is called when the button is clicked.
public void actionPerformed (ActionEvent click)
{
// Retrieve the string, if any, that was typed into the textfield:
name = inputField.getText ();
// ...
}
public void paint (Graphics g)
{
// The Face, as before:
// ...
String greeting = "Hello " + name; // Combine these two strings into one.
g.drawString (greeting, 190,150); // Draw the greeting
}
}
Note:
- A variable needs to be declared, as in:
public class FaceWithGreeting extends Applet implements ActionListener {
// A String variable to hold the name when it has been entered.
String name;
// ...
}
- The declaration has a type (String in this case)
followed by an identifer (name).
- The type can be a Java reserved word specifying a type
such as int, boolean or double. Example:
int myAge;
- The type can be a Java library object such as String
in our example.
- The type can be an object that we have defined (this is a
little advanced - we'll need to learn about objects first).
- The type is followed by an identifer of our choosing.
- We could have, if we liked, called our name identifer someThingummitWhatever:
public class FaceWithGreeting extends Applet implements ActionListener {
// A String variable to hold the name when it has been entered.
String someThingummitWhatever;
// ...
}
- But then, we should be sure to use this every place we refer
to the identifier:
// ... left out the import's for illustration ...
public class FaceWithGreeting extends Applet implements ActionListener {
// A String variable to hold the name when it has been entered.
String someThingummitWhatever;
public void init ()
{
//-----------------------------------------------------------
// ... left this out for illustration ...
//-----------------------------------------------------------
// Initially the string that's in the someThingummitWhatever variable should be
// blank because that's what we'll print before a name is entered.
someThingummitWhatever = "";
}
// The method actionPerformed is called when the button is clicked.
public void actionPerformed (ActionEvent click)
{
// Retrieve the string, if any, that was typed into the textfield:
someThingummitWhatever = inputField.getText ();
// ...
}
public void paint (Graphics g)
{
// The Face, as before:
// ...
String greeting = "Hello " + someThingummitWhatever; // Combine these two strings into one.
g.drawString (greeting, 190,150); // Draw the greeting
}
}
- Variables can be declared in many places:
- They can be declared at the top level as in the
variable name or locally as in the variable
greeting:
public class FaceWithGreeting extends Applet implements ActionListener {
// A top-level declaration, inside the outermost braces.
String name;
public void init ()
{
// ...
// Top-level variables can be accessed anywhere inside the class.
name = "";
}
public void actionPerformed (ActionEvent click)
{
// Another access:
name = inputField.getText ();
// ...
}
public void paint (Graphics g)
{
// ...
// A local declaration:
String greeting = "Hello " + name; // Combine these two strings into one.
// ...
}
}
- You can combine declaration and an initial value or leave
them separate.
- Above, name is declared and then initialized
separately and greeting is declared and initialized in
one statement.
- Here's how we could do greeting differently:
public void paint (Graphics g)
{
// ...
// A local declaration:
String greeting;
greeting = "Hello " + name; // Combine these two strings into one.
// ...
}
- How do we know when to declare a variable as top-level
vs. locally?
- Generally, if you have few variables, you can declare all of
them at the top-level.
- For example, the above program would work fine, if we
declared greeting at the top level:
public class FaceWithGreeting extends Applet implements ActionListener {
String name;
String greeting;
public void init ()
{
// ...
name = "";
}
public void actionPerformed (ActionEvent click)
{
name = inputField.getText ();
// ...
}
public void paint (Graphics g)
{
// ...
greeting = "Hello " + name; // Combine these two strings into one.
// ...
}
}
- The name variable had to be declared at the
top-level because it was accessed in multiple methods.
- The variable greeting was declared locally because
it was not needed anywhere else.
- For an intro course, it's quite alright to declare all
variables at the top level.
- Later, as you get more sophisticated, you'll learn to declare
variables only where they are needed.
Other kinds of variables:
- We did not cover all variables in our example.
- For completeness, let's identify every single variable in the
program:
// ...
public class FaceWithGreeting extends Applet implements ActionListener {
// A String variable to hold the name when it has been entered.
String name;
// The text field in which the user enters a string.
TextField inputField;
public void init ()
{
//-----------------------------------------------------------
setLayout (new BorderLayout());
Panel bottomPanel = new Panel ();
Label nameLabel = new Label ("Enter your name: ");
bottomPanel.add (nameLabel);
inputField = new TextField (15);
bottomPanel.add (inputField);
Button nameEnteredButton = new Button ("Press when done");
bottomPanel.add (nameEnteredButton);
nameEnteredButton.addActionListener (this);
add (bottomPanel, BorderLayout.SOUTH);
//-----------------------------------------------------------
name = "";
}
public void actionPerformed (ActionEvent click)
{
name = inputField.getText ();
// ...
}
public void paint (Graphics g)
{
// The Face, as before:
g.drawOval (40,40, 120,150); // Head
g.drawOval (57,75, 30,20); // Left eye
g.drawOval (110,75, 30,20); // Right eye
g.fillOval (68,81, 10,10); // pupil (left)
g.fillOval (121,81, 10,10); // pupil (right)
g.drawOval (85,100, 30,30); // Nose
g.fillArc (60,125,80,40, 180,180); // Mouth
g.drawOval (25,92, 15,30); // Left ear
g.drawOval (160,92, 15,30); // Right ear
// The greeting:
g.drawOval (160,125, 150,40); // An oval for the greeting.
String greeting = "Hello " + name; // Combine these two strings into one.
g.drawString (greeting, 190,150); // Draw the greeting
}
}
- There are object variables such as inputField and nameEnteredButton.
- There are parameter variables such as g.
- We can choose our variable names. To illustrate, let's re-write
the whole program with different variable names:
// ...
public class FaceWithGreeting extends Applet implements ActionListener {
// A String variable to hold the name when it has been entered.
String someThingummitWhatever;
// The text field in which the user enters a string.
TextField theField;
public void init ()
{
//-----------------------------------------------------------
setLayout (new BorderLayout());
Panel panelAtTheBottom = new Panel ();
Label labelForTheName = new Label ("Enter your name: ");
panelAtTheBottom.add (labelForTheName);
theField = new TextField (15);
panelAtTheBottom.add (theField);
Button buttonForClicking = new Button ("Press when done");
panelAtTheBottom.add (buttonForClicking);
buttonForClicking.addActionListener (this);
add (panelAtTheBottom, BorderLayout.SOUTH);
//-----------------------------------------------------------
someThingummitWhatever = "";
}
public void actionPerformed (ActionEvent click)
{
someThingummitWhatever = theField.getText ();
// ...
}
public void paint (Graphics theGraphicsObject)
{
// The Face, as before:
theGraphicsObject.drawOval (40,40, 120,150); // Head
theGraphicsObject.drawOval (57,75, 30,20); // Left eye
theGraphicsObject.drawOval (110,75, 30,20); // Right eye
theGraphicsObject.fillOval (68,81, 10,10); // pupil (left)
theGraphicsObject.fillOval (121,81, 10,10); // pupil (right)
theGraphicsObject.drawOval (85,100, 30,30); // Nose
theGraphicsObject.fillArc (60,125,80,40, 180,180); // Mouth
theGraphicsObject.drawOval (25,92, 15,30); // Left ear
theGraphicsObject.drawOval (160,92, 15,30); // Right ear
// The greeting:
theGraphicsObject.drawOval (160,125, 150,40); // An oval for the greeting.
String greetString = "Hello " + someThingummitWhatever; // Combine these two strings into one.
theGraphicsObject.drawString (greetString, 190,150); // Draw the greeting
}
}
In-Class Exercise:
Add some color to the above applet. Make the greeting more interesting.
In-Class Exercise:
Make the "Hello" string and the name appear on different lines
in the applet.
Assignment
The = symbol is used to assign values to variables:
- For example, the statement
name = "";
assigns the empty string to the variable name.
- Similarly, the variable greeting below is assigned
the value resulting from concatening the string "Hello " with
whatever string is stored in name:
String greeting = "Hello " + name; // Combine these two strings into one.
- Likewise, we called the method getText() in the object
inputField. This method returns a string, which
we assign to the variable name:
// Retrieve the string, if any, that was typed into the textfield:
name = inputField.getText ();
- The assignment symbol = is called an operator
in Java. Other operators include arithmetic ones such as: +, -,
* and /.
In-Class Exercise:
Examine the compiler error you get if you accidentally remove the
= operator in any of its uses above.
In-Class Exercise:
Examine the compiler error you get if you accidentally remove the
; (semicolon) at the end of assignment statements.
Multiple inputs
Let's create an applet with two inputs:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class FaceWithGreeting2 extends Applet implements ActionListener {
// String variables for name and salutation:
String name;
String salutation;
// The text fields in which the user enter strings.
TextField nameField;
TextField salutationField;
public void init ()
{
// -------------------------------------------------------------
// GUI stuff
setLayout (new BorderLayout());
Panel bottomPanel = new Panel ();
Label nameLabel = new Label ("Name: ");
bottomPanel.add (nameLabel);
nameField = new TextField (15);
bottomPanel.add (nameField);
Label salutationLabel = new Label (" Salutation: ");
bottomPanel.add (salutationLabel);
salutationField = new TextField (10);
bottomPanel.add (salutationField);
Button doneButton = new Button ("Press when done");
bottomPanel.add (doneButton);
doneButton.addActionListener (this);
add (bottomPanel, BorderLayout.SOUTH);
// -------------------------------------------------------------
// Initial values:
name = "";
salutation = "";
}
// The method actionPerformed is called when the button is clicked.
public void actionPerformed (ActionEvent click)
{
// Retrieve the strings from the two text fields:
name = nameField.getText ();
salutation = salutationField.getText ();
// Redraw the applet:
repaint ();
}
public void paint (Graphics g)
{
// The Face, as before:
g.drawOval (40,40, 120,150); // Head
g.drawOval (57,75, 30,20); // Left eye
g.drawOval (110,75, 30,20); // Right eye
g.fillOval (68,81, 10,10); // pupil (left)
g.fillOval (121,81, 10,10); // pupil (right)
g.drawOval (85,100, 30,30); // Nose
g.fillArc (60,125,80,40, 180,180); // Mouth
g.drawOval (25,92, 15,30); // Left ear
g.drawOval (160,92, 15,30); // Right ear
// The greeting oval:
g.drawOval (160,125, 150,40);
// Combine the strings into one:
String greeting = "Hello " + salutation + " " + name;
// Draw the greeting:
g.drawString (greeting, 190,150);
}
}
Note:
- We have used two text fields, one for a salutation and one for
the name.
- Similarly, we used two String variables.
- The + operator can be used for concatentation multiple
times in a single statement.
- We will need to widen the applet by increasing the "width"
parameter in the HTML file:
<HTML>
<BODY bgcolor="#FFFFFF">
<p>
Enter your name and preferred salutation in the two text fields at the bottom below
and then press the button.
<p>
<applet code="FaceWithGreeting2.class" width=600 height=300>
</applet>
</body>
</html>
- Link to applet
In-Class Exercise:
[Challenging exercise] Can you make the face initially without a smile, and then make it
smile when the greeting is displayed? Hint: use int
variables to store some of the oval parameters, and set those values
in the actionPerformed method. This way, the initial values
(set in init) are for no-smile, and the new values set
in actionPerformed are for a smile.