Lab 8
MeAndEclipse
  Ex 1:
Month Names
  Ex 2:
MeAndJava GUI
  Ex 3:
GUI Month Names
  Ex 4:
Adding turtles
  Ex 5:
How to submit?
Policies
Back to labs

Lab 8!

MeAndEclipse

In this lab you are going to

  • Review the basics of the Eclipse IDE,
  • Learn the basics of commandline non-GUI Java programming,
  • Remind yourself how to create a GUI application in Java,
  • Modify the month abbreviations program so it prints the entire month name, not just the first three letters
  • Make a GUI version of a month names program

Let's begin by firing up Eclipse. Do that by double clicking the desktop icon (Windows) or selecting the Eclipse icon from the dock (Macintosh).

You will be confronted with a dialog.

Satisfy the dialog by providing sensible information about where you want your workspace etc. I suggest that you use a name like lab8 for the package you use this week.

So that you get comfortable with Eclipse I want you to create a program that will print your name and your current opinion of Eclipse. Let's begin by examining the program I want you to write:

public class MeAndEclipse {

        /**
         * @param args
         */
        public static void main(String[] args) {
                System.out.println("_________________");
		System.out.println("I ********* Eclipse");
        }
}

As we shall see, Eclipse will prepare some of these lines of code for you. And it will create code identifying the package. You are responsible for replacing _________________ with your own name and for replacing ********* with words to express your opinion of the Eclipse IDE. You can substitute "love", "like", "dislike", "hate" or whatever you want to make your feelings known!

Here is a line-by-line breakdown of the meaning of the above program:

  • public class MeAndEclipse gives a name MeAndEclipse to the program. Every program in Java is a class and it needs to be public so that it can be run. This line of code will be generated for you by Eclipse when you have responded in a dialog with the name of the class.
  • /** * @param args */ These three lines are a JavaDoc comment. Again these lines will be automatically generated for you by Eclipse.
  • public static void main(String[] args). This line will also be automatically generated as long as you remember to check a box. Commandline programs like this one must have a main method and it must be written exactly like this.
  • System.out.println("_________________"); and
  • System.out.println("I ********* Eclipse"); These are the two lines of code you will have to type yourself. System.out is the name of an object that can output strings to the console. println is one of its methods and the string is an argument that you provide to satisfy the method's parameter.

OK. Let's create this program in Eclipse. You should have an Eclipse window open as well as the browser in which you are reading these instructions. You can use Alt-TAB (Windows) or Apple-TAB (Mac) to toggle between the windows. Do it now for practice.

When in Eclipse you will see a menu bar along the top including items File, Edit, Source ... Choose the "File" option and from that choose "New" and from that choose "Java Package".

You can choose a name for your project (I suggest lab8).

Now within your package you are going to create your first program. From the "File" menu, again choose "New" but this time select "Class". You will name your class MeAndEclipse.

Be sure to check the box that says you want a method stub created for public static void main(String[] args). When you click "Finish" you should see:



Exercise 1

Replace the auto-generated comment "// TODO Auto-generated method stub" with the two println statements given above. Then save (this will compile the program or inform you about any errors). Then Run your program. Congratulations!





Month names

MonthAbbreviations.java lists the month abbreviations program which asks the user for a number in the range 1 - 12 (say 9) and returns the 3-letter abbreviation for the corresponding month's name (say Sep). To review how to use Eclipse, let's just paste the program as is into Eclipse.

Let's begin by firing up Eclipse and creating a new package for this exercise, named months and create a new class MonthAbbreviations. Now copy the code from the listing MonthAbbreviations.java into the appropriate window in Eclipse and save it.

Now run the program and check that it works as advertised.

For our first exercise we want to adapt that month abbreviations program so that it prints the full name of the month given its number, rather than just the three-letter abbreviation. The new program will be similar enough to the existing program that you should begin with a copy of the existing program.

Choose the "Save as" option and save the current Java class file with the name MonthNames. Then edit the first few lines so it will read:

/** MonthNames.java reads a number from 1-12 and displays
 * the full name of the corresponding month.
 */
 import java.util.Scanner;

 public class MonthNames {
         public static void main(String[] args) {
                 // Print a message to the console screen
                 System.out.println("To see the name of a month,");
                 System.out.print(" enter a month number (1-12): ");
                 // Get the month number through the keyboard
                 Scanner keyboard = new Scanner(System.in);
                 int monthNumber = keyboard.nextInt();
                 // Compute the month name
                 final String MONTH_TABLE = "JanuaryFebruaryMarchAprilMayJune" +
                 "JulyAugustSeptemberOctoberNovemberDecember";

When all the month abbreviations had exactly three letters, it was easy to calculate a start and stop so that you could extract the appropriate substring for display. Now it's not so easy:

  • One month has only three letters
  • The longest month name has 9 letters
  • There is no sensible pattern to the lengths of the names of the months that would enable you to create a simple formula.

One approach to solving this problem is to pad all the month names with enough spaces so they will all be nine letters long. You would rewrite

                 final String MONTH_TABLE = "JanuaryFebruaryMarchAprilMayJune" +
as
                 final String MONTH_TABLE = "January  February March    April    May      June     " +
and the next line similarly. You should then change the formulae for start and stop to reflect the fact that each month now has been allocated nine characters in MONTH_TABLE, not three. You should also, in the interests of accuracy, change the name of the variable from monthAbbreviation to monthName. When you have made all those changes, you should find that your program runs like this:
To see the name of a month,
 enter a month number (1-12): 7

Month #7 is 'July     '.

You are probably uncomfortable with the five spaces after July before the closing apostrophe. You would prefer to see:

To see the name of a month,
 enter a month number (1-12): 7

Month #7 is 'July'.


Exercise 2

Write a program to prompt the user for a month number (between 1 and 12) and to display the month's name as above. Hint: Consult the Java API documentation about the class String and look for a method called trim.





MeAndJava GUI

Let's do the equivalent program, but make it GUI. Instead of System.out.println let's make stuff appear in a more friendly place. This is more like Alice.

In Alice you start with a world and you add characters from a gallery, and then you add instructions to make what you want happen. In GUI Java we'll start with a javax.swing.JFrame and we'll add objects from a Java library, then we'll add instructions to make what we want happen.

Begin in Eclipse by choosing New->Class. In the dialog for the new class you'll set the name (MeAndJavaGUI) and tell it about the superclass javax.swing.JFrame. You will want a public static void main stub because you're creating an application rather than an .

You can save it and run it if you like, but nothing will happen. Just like an empty world in Alice, you have not told it to do anything, so the play button does nothing.

To make things happen, we need to construct a MeAndJavaGUI object.

You need a constructor for the MeAndJavaGUI class so Java will know what to do when the main method creates a MeAndJavaGUI object. Type in (or copy and paste) the following constructor:

public MeAndJavaGUI() {
  super("MeAndJavaGUI");
  setSize(400,400);
  setDefaultCloseOperation(EXIT_ON_CLOSE);
  setVisible(true);
}
Also replace the comment in the main method by a statement that calls the constructor of the class.

Save your code and run.

Now here's an explanation for what you just did.

  • super("MeAndJavaGUI") calls the constructor of the parent class (JFrame) and passes it the value "MeAndJavaGUI" for its parameter. Consult the The Java API documentation and you will see that this will create a JFrame with the word MeAndJavaGUI in its title bar.
  • setSize(400,400) sets the size of the JFrame (duh!).
  • setDefaultCloseOperation makes the "go away" box work.
  • setVisible(true) is necessary so the JFrame will appear on your screen.

We are going to make a button appear in our JFrame that has our name on it. And a second button that has a label matching our opinion of Java so far. First of all we need to declare the button objects. We need to import the JButton class, so we say:

import javax.swing.JButton;
and place that right after the other import statement. Then we declare:
private JButton myName, myComment;
That line can go after the header public class ... but before the constructor public MeAndJavaGUI(). It declares an instance variable of type JButton (which is to be found in the package (or, as you would say in Alice, in the gallery) javax.swing).

If you declare the JButtons first, before the import, Eclipse would detect the error and prompt you to add the import statement.

Next we need to actually create JButton objects. That means calling a constructor of the JButton class. Go ahead, check out the documentation and find the constructor that lets you set the label as you create the button. To make the button with your name, you'll need to code:

myName = new JButton("Huckleberry Hound");

Don't forget you'll need a similar statement to create the button whose label reflects your opinion of Java.

Now we need to cause the JButtons to appear in the content pane of the JFrame (that is the part of the JFrame that's not taken up with title bar, borders, etc.) and to have a label that corresponds to your name. The class Container is to be found in the java.awt package (Go ahead, check it out!) so we'll need:

import java.awt.Container;
and we're also going to need a layout manager to make it all look nice so we'll
import java.awt.FlowLayout;

We'll declare a variable to refer to the content pane, so we can give it a layout manager:

		Container contentPane;
		contentPane = getContentPane();
		contentPane.setLayout(new FlowLayout());

We'll add the buttons and call validate to make sure it appears.

		contentPane.add(myName);
		validate();

I bet you can figure out how to add the second button.

Exercise 3

Add all the code described above. Test the program and make sure it does what you expect. Most importantly, add comments to the code that make it clear to the grader that you understand what you are doing and help the reader understand the code.





GUI Month Names

Create a new class in your project named GUIMonthNames, with superclass javax.swing.JFrame, and with a method stub for public static void main(String[] args). As in the last lab write a constructor that does all the usual housekeeping:
public GUIMonthNames() {
  super("Month Names: GUI version");
  setSize(400,400);
  setDefaultCloseOperation(EXIT_ON_CLOSE);
  setVisible(true);
  Container myPane = getContentPane();
  myPane.setLayout(new FlowLayout());
}
Be sure to import the usual classes, or let Eclipse write the import statements for you. If you are interested in cutting down on the number of imports at the start of your program, you can use the wildcard *. For example, if you import javax.swing.* there is no need for any more imports from that package. You will not need to write import javax.swing.JFrame nor import javax.swing.JButton because the import javax.swing.* already covers them.

Doesn't that bloat the size of your compiled code on account of importing all the classes from a package, not just the specific ones that you need?

No. The point about the import statement is that it's just a guide for the compiler to know where to look for classes that do not have their full package name. The full package name of JButton is actually javax.swing.JButton. Because of the import statement you can declare simply JButton myButton = new JButton("my name"); instead of the full javax.swing.JButton myButton = new javax.swing.JButton("my name"); It's interesting to note that the second form would work even in the absence of any import statement.

So, express your preference either with:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
or by letting Eclipse write a separate statement for each class you wish to import, or (if you are particularly masochistic or wish to annoy the graders) you can use the fully qualified class name throughout your program.

Also be sure to call the constructor by adding new GUIMonthNames(); to the main() method. Now let's tell the user story:

  1. The user is faced with a message requesting "Enter a number (1 - 12) below".
  2. The user should enter a number in a text field
  3. When the user hits the Enter key the month number is replaced by the month name

I want you to use a JLabel (see the documentation) to provide the user instructions. I want you to use a JTextField to input the number and output the results. Accordingly, you declare:

	private JLabel instructions;
	private JTextField data;
and add these lines to the constructor:
		instructions = new JLabel("Enter a number (1-12) below");
		data = new JTextField(20);

To see the meaning of the 20 as an argument to the JTextField constructor you should consult the API documentation.

At this point you should compile and run your program.

Of course nothing works yet!

Exercise 4

Make your GUI program work by adding an action listener to the JTextField.

		data.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int monthNumber = new Integer(data.getText());
				// add your code here
			}
		});
You will need to add the code from the main method of your non-GUI program from the previous exercise. Mostly it will be unchanged, but there will be some small modifications:
  • You still need the constant MONTH_TABLE just as before
  • You still need the int start and int stop just as before
  • You still need to compute the String monthName just as before
  • Instead of printing to System.out you will simply set the text of the JTextField data using data.setText(...)
  • You also won't need the linefeed in the output text
That's it: Just enter the code into the body of the actionPerformed method.




Adding turtles

Over to you!

Exercise 5

Add a button to the turtle world, and each time the button is pressed, add an (with a random color) at a random place in the world.

See what happens after you add a dozen turtles and when you try to control through the keyboard and the mouse?!







How to submit your homework

Create a folder on your computer and name it 'CS053-Spring10' (if you do not have it already). Create another folder and name it 'lab8'. In the newly created 'lab8' folder copy your solutions to the exercises: Exercise1.java, Exercise2.java, Exercise3.java, and so on...

Next, go back up to your folder 'CS053-Spring10', right click on your folder 'lab8' and compress it either in a or file.

Your newly compressed file should be named:

  • FirstName_LastName_Lab_8.zip or
  • FirstName_LastName_Lab_8.rar

After you have compressed your homework, then proceed to submit it via Blackboard.

Got problems? If you have any problems make sure you clear them with your lab instructor because if you do not follow these requirements for submission your lab homework submissions will not be accepted and you will get zero points.