We are going to develop a program that will open a new window on your screen and, when you click the mouse button, it will deliver a message in that window. Also this time, we are going to extend the JFrame class. A JFrame is a lot like a JApplet except that, whereas a JApplet is usually viewed in a Browser (like Firefox or Safari) a JFrame is a standalone program. JFrame programs need a main method to create the initial object (we'll see why later).
Get to your workbench. It will look something like:
Don't create a new project. We'll continue in the same project. It's time to create a new Java class. Again from the File menu select New class giving you a dialog like this:
You will notice that I:
I was told that the use of the default package is discouraged. Ah well, let's live with that discouragement for now! If you want to know more about JFrame and MouseListener then you must read The Java API documentation where you can look up the JFrame class and the MouseListener interface.
You will also observe, when you look in your Eclipse workbench, that a great deal of code has been written for you:
If you get that warning about "The serializable class Ex2 does not declare..." then you did not heed my suggestion to set your preferences to ignore this warning. Never mind, it won't hurt.
The reason for this is that when you say that your class will implement the MouseListener interface, you are promising to write code for all the methods specified in the interface.
In Alice terms, an interface is a kind of blueprint for a class. It specifies what methods must be present for the class to be created. A MouseListener must provide methods for five different kinds of mouse events: mouseClicked, mouseEntered, mouseExited, mousePressed and mouseReleased. Currently the methods are empty, which means that nothing is going to happen when you click the mouse! We're going to fix that.
Begin by adding an instance variable called message to your class. It will be a String and will initially be empty. So, right before the line
public void mouseClicked(MouseEvent arg0) {write the declaration:
private String message = new String("");
And now, we are going to write code so that the value of the String variable message will change from "" (the empty string) to "Ouch! don't click me so hard!" when you click the mouse button.
You need to do some typing so that
becomes