January 29, 10 points
In this exercise you will make write an applet that displays the string "Goodbye World! Hello Java!" in various colors. The applet has a button labeled "Text Color" that can be used to cycle though the colors black, blue, and red.
Doing this exercise requires editing two class files TextPanel.java and TextApplet.java. The first defines a TextPanel class. An object in this class draws a text string on a panel (a region inside a window). It provides a changeTextColor() method that can be invoked by another object to change the color of the text.
The second class file defines a TextApplet class. An object in this class places a button and a text panel inside an applet, and sets up the button so that it causes the text panel's changeTextColor() method to be invoked when the button is pressed.
As with all applets, you will also need to write a HTML file to tell the appletviewer program what to do.
The steps below describe construction of the program, broken down into small editing changes. Each editing step contains an explanation of the code that you are adding. It is important to understand most of these explanations. The terminology that is used in the steps will be used a lot in future lab exercises and programming assignments.
Start up the emacs editor and open a new file named TextApplet.html. Enter the following text.
<html> <head> <title> Text Applet </title> </head> <body> Lab Exercise 1<br> CS 2121 Section {your section goes here}<br> {your name goes here}<br> <hr> <applet code="TextApplet.class" width=400 height=150 > </applet> <hr> </body> </html>
After you have entered the text, be sure to save it.
In most future assignments, you will need an HTML file like this. You can start with a copy of this file. You only need to change the title, the exercise or assignment, the name of the class, the width, and the height.
In your editor, open a new file named TextApplet.java. Put the following code into the file.
// Programming Assignment 1 // CS 2121, Section {your section goes here} // {your name goes here} import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TextApplet extends JApplet { public void init() { } }
After saving the file contents, you can compile the TextApplet class to check for errors. Now, run the applet with appletviewer. You should see just a blank applet. Nothing will appear in the applet until some code is added to its init method.
In your editor, open a new file named TextPanel.java. Put the following code into the file.
// Programming Assignment 1 // CS 2121, Section {your section goes here} // {your name goes here} import java.awt.*; import javax.swing.*; public class TextPanel extends JPanel { }
After saving the file contents, you can compile the TextPanel class to check for errors. At this time, you still do not have any code in the init() method of the TextApplet class, so you won't gain any information by running the applet with appletviewer.
public TextPanel() { setPreferredSize(new Dimension(350, 100)); }
The name (here it is TextPanel) is always the same as the class name. Whenever a new text panel is created, the constructor code is executed. This constructor code specifies that the text panel has a preferred size of width 350 and height 100. This information is used by layout managers, which determine the location and size of visual components in your applet.
After saving the file contents, you can compile the TextPanel class to check for errors.
The two variable definitions below should be added in order between the curly braces ("{" and "}") of the TextPanel class definition. They are called instance variable because they can be used anywhere in an object of this class (an instance of the class).
Color[] textColors = new Color[] { Color.black, Color.blue, Color.red };The first occurence of Color[] specifies what kind of data that the variable holds. The name of the variable is textColors. The square brackets ("[" and "]") in the type indicate that this variable is an array variable. An array variable holds multiple pieces of data of the same type, each associated with a number called an index. The indices (that's the plural of index) range from 0 to one less than the number of data pieces. With Color[] as its type, the variable is an array of Color objects.
The expression new Color[] creates the array and the list that is enclosed in curly braces specifies the initial contents of the array This array has three pieces of data: the color black, the color blue, and the color red. Their indices are 0, 1, and 2, respectively. The semicolon (";") at the end is a required part of any variable definition. It signals the end of the definition.
int textColorCode = 0;The int indicates that the variable, named textColorCode, is an integer (whole number). Its initial value is set to 0. It will be used as an index for the textColors array to select the text color.
After saving the file contents, you can compile the TextPanel class to check for errors.
public void changeTextColor() { textColorCode = (textColorCode + 1)%textColors.length; repaint(); }This method is writen for the sake of the text applet. When the user clicks on the text color button in the applet, the applet will invoke this method to change the color.
The percent sign ("%") is a Java operator that combines two numbers, with the remainder of a division as its result. Here, textColors.length (the number of data pieces in the textColors array) is divided into textColorCode + 1. The remainder is assigned as the new value for the textColorCode variable. With three colors in the array, the effect is that textColorCode is incremented by one if it was 0 or 1, but reset to 0 if it was 2. That is, with successive invokations of this method, textColorCode is cycled through the values 0, 1, and 2, which are the valid indices for the textColors array.
The second statement in the method ensures that the text panel is redrawn whenever the method is invoked. This will result in invoking the paintComponent() method of this class, which is described in the next step.
After saving the file contents, you can compile the TextPanel class to check for errors.
public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(textColors[textColorCode]); g.drawString("Goodbye world! Hello Java!"); }The paintComponent() method is automatically invoked whenever the panel or the applet is repainted. For example, when an applet is covered by another window, and then uncovered, it needs to be repainted. An applet or one of its visual components can also be repainted under program control by invoking its repaint() method.
Since the TextPanel class inherits from the JPanel class, there is already an implementation for its paintComponent() method. The first statement, super.paintComponent(g);, ensures that the JPanel implementation is invoked before anything else is done. Strange things happen if you omit this statement.
When paintComponent() is invoked, a graphics object for the component is provided for drawing. All drawing on a component is done with messages sent to the graphics object. Here, the graphics object is told to use the color selected from the textColors array for drawing, then told to draw the text string "Goodbye world! Hello Java!".
After saving the file contents, you can compile the TextPanel class to check for errors.
At this point, you are ready to finish coding the TextApplet class. Reopen the emacs buffer for the TextApplet.java file. The following Java statements should be added in order between the curly braces of the init() method.
getContentPane().setLayout(new FlowLayout());The text applet is a container, which means that it can contain a variety of visual components. This statement determines how the applet's components are located and sized. It creates a flow layout manager and uses it as the layout manager for the text applet. A flow layout manager places components in rows, putting as many components as it can fit into each row. When a row is full, a new row is started. Each component given its preferred size.
The content pane is an important difference between Swing components and the older AWT components. Swing top-level containers (JApplet, JFrame, and other less frequently used containers) all have a content pane. Visual components should be added to the content pane and layout managers should be installed in the content pane.
final TextPanel textPanel = new TextPanel();Here you are creating a text panel and assigning it to the textPanel variable. It will be used to display text.
Since this variable is declared inside a method, it can only be used inside that method. For that reason, it is called a local variable.
JButton textColorButton = new JButton("Text Color");Here, you are creating a button with label "Text Color" and assigning it to the variable textColorButton. Like textPanel, this is a local variable.
textButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textPanel.changeTextColor(); } });This statement sets up a response for the text color button. When the user clicks on the button, the button invokes the actionPerformed() method for all of the action listeners that have been added. If no action listeners have been added then nothing happens when the button is clicked.
The syntax starting with new ActionListener() takes some getting used to. It is creating a new unnamed class whose definition is between the first and last curly braces. It is also creating a new instance (object) of that class.
getContentPane().add(textColorButton);Here, you are adding the button into the applet (through its content pane). The layout manager will take determine its size and location. If you forget this statement, the button will not appear in the applet.
getContentPane().add(textPanel);Finally, you add the text panel. The layout manager (a flow layout) tries to add the text panel into the same row as the button, but finds that the applet is not wide enough. Thus it starts a new row. This results in two rows; the first just contains the button, the second just contains the text panel. If the applet were larger, both would be placed into a single row.
After saving the file contents, you can compile the TextApplet class to check for errors. Then run the applet with appletviewer. Your applet should look like the one in the following link. If it does then you are ready to have your applet validated.
Get the attention of your instructor or TA and run your applet with appletviewer. After your applet has been validated, you should turn in copies of your TextApplet.html, TextApplet.java, TextPanel.java. Be sure your name, the course number, and your section number appear in each file.
If your read over this web page after completing the exercise, it will help you to solidify the things that you have learned. I don't expect you to remember everything. Try to focus on two main aspects: the "big picture" of building applets and the terminology for describing the code construction.
There are four important parts of the big picture:
The folowing are five important phrases used for describing code construction: