Thursday, December 31, 2009

Buttons in Java Applets

 
 Buttons in Java Applets

* Creating a button object
* The concept of the "event driven program"
* The action() method
* The position of buttons on the screen
* Summary of buttons

Buttons are the small grey (usually) rectangles that you see appearing on the screen occasionally. They crop up in several languages, and even appear on web pages, such as the button that you see below:

We can create a button in a Java applet using something called a Button object. This button will always appear at the top of the screen in the centre (unless you use something called a canvas or a frame - more about these once I have worked out exactly how to use them myself!) and you can specify exactly what action the button carries out when you click on it.
Creating a button object

Unlike variables such as numbers (declared with int, float or double) or strings (declared with String), declaring objects is a two-stage process. I say "objects" rather than "button objects" because you will find that what I am about to show you will apply to a great many things in Java, not just button objects. However, for the time-being, we will stick to button objects.

* Firstly, declare the object exactly as you would declare a normal number, except this time, the variable type is Button:

Button clickOnMe;

This variable declaration should go with all the other declarations just inside the curly brackets used to set up the main program. The order in which you put your variable declarations isn't important - the button declaration can go at the beginning of the declarations, at the end or somewhere in the middle.
* Create a special method called init() as follows, and put in it the following instruction:

public void init ()
{ clickOnMe = new Button("Here's a button!");
add(clickOnMe);
}

init() is a special method that is called automatically by Java when you first run the applet. It is used to set up variables (to initialise them - hence the name) and to call up any methods that you want called immediately. It is the same method init() that you met in the last section.

There are two commands inside init() that you haven't met before. The first one reserves space in the memory for the button object. So far we have declared it (i.e. told Java that we intend to use a variable called clickOnMe, but we haven't actually reserved the memory for it. That is what this new Button instruction does. It is always followed by a pair of brackets and inside those is the caption that you want to appear on the button. In this case, the caption is "Here's a button!"

The add(clickOnMe) instruction actually makes the button appear on the screen. If you didn't include it, then the button would be created but would remain invisible. Here is the complete program:

import java.applet.*;
import java.awt.*;

public class buttonDemo1 extends Applet
{ Button clickOnMe;

public void init ()
{ clickOnMe = new Button("Here's a button!");
add(clickOnMe);
}
}

You will notice that (a) there is nothing on the screen except the button (and it doesn't do anything when you click on it!) and (b) the button still appears on the screen even though we didn't include a method called paint(Graphics g).
In fact, the add(clickOnMe) instruction causes the button to appear whether or not you put in a paint(Graphics g) method or not. Even if you alter various things about the button (such as its caption), then you still don't need paint() to update the button on the screen - it will just update automatically.

You can add more buttons if you like. In this following example, I have put in two buttons and an integer variable. Both the buttons are declared in the same Button statement, but there is no reason why you can't declare them on separate lines:

import java.applet.*;
import java.awt.*;

public class buttonDemo2 extends Applet
{ Button increase, decrease; // These are two buttons
int value = 1000;

public void init ()
{ increase = new Button("Increase the value");
add(increase);
decrease = new Button("Decrease the value");
add(decrease);
}

public void paint (Graphics g)
{ g.drawString("The value is currently " + value, 50, 80);
}
}

This time I have included a paint() method, but you will notice that it does not include any reference to the buttons at all. All it does is display the value of the variable value together with a simple message.

This program displays the two buttons and the variable, but it does not tie those buttons to actions. How do we get the buttons to do something? In the next two sections we will see how this is done by adding an extra method to that program I have just given you.
The concept of the "event driven" program

A Java applet is a type of program called "event driven." This will be familiar to anyone who has programmed in JavaScript or Visual C++ but less so to programmers coming from languages such as (ordinary) C++ or Pascal. It is best described using an analogy.

Suppose I am expecting a visitor to arrive at my front door. Unfortunately, I do not have a door bell or a door knocker, so I have to spend the time standing by the front door waiting for him to call. If I don't stand by the door, there is the possibility that he will arrive and then go away again - I will have missed him.

Some programs work this way. To see if you are clicking on a button, they continually have to check the status of the buttons at regular intervals. This makes them rather inefficient, since it cuts down the time they have available to do other things.

Now I get a doorbell fixed. This time, when my friend arrives, all he has to do is press the doorbell. I will break off from watching the television, doing the crossword, or picking my nose (i.e. whatever I am doing) and come running. This is what an event-driven program does. It carries on with whatever it is doing until you click on a button (or cause some other event to happen). Then it deals with that button click (or whatever) and goes back to what it was doing before.
The action() method

There is a special method called action() which is designed entirely to deal with button clicks. You do not have to call it specifically - it is called automatically whenever an event , such as a button click occurs. Although it can't trap all events (in particular, mouse clicks elsewhere on the screen, i.e. apart from on buttons - we track those using a different method), it can deal with most of them. Here is the program with the correct method added:

import java.applet.*;
import java.awt.*;

public class buttonDemo3 extends Applet
{ Button increase, decrease; // These are two buttons
int value = 1000;

public void init ()
{ increase = new Button("Increase the value");
add(increase);
decrease = new Button("Decrease the value");
add(decrease);
}

public boolean action (Event e, Object args)
{ if (e.target == increase)
value++;
if (e.target == decrease)
value--;
repaint();
return true;
}

public void paint (Graphics g)
{ g.drawString("The value is currently " + value, 50, 80);
}
}

A lot of that will be new to you so I will go through it one point at a time:

* Firstly, the action() method takes two parameters. The first one is of type Event and the second one is of type Object. I have chosen to call these e and args, simply because that is what I saw them called in the Java book that I read. You can call them anything, but you must include both of them, and you must specify that the first is of type Event and the second is of type Object. (In fact, we don't actually use the second parameter at all inside the method, but we must include it or Java will not recognise the method when we click on a button).

* The function action() is not marked as void as all the functions have been that you have met up to now. Instead, it returns a boolean value. You will notice that the last line of function is return true. boolean values are either true or false, and in this case, the standard thing to do is to return a true value at the end of the action() method. Why do we do this? Because that is what Java expects in this particular circumstance!

* We have two possible events that can happen - clicking on increase or clicking on decrease - and we need to distinguish between them. Fortunately, the Event variable (which I have called e) can tell us. It is an object with a property called target, and we use two if statements to distinguish whether the increase button was clicked or the decrease button.

In this case, if the increase button is clicked, the value of the variable is increased (as specified by value++) and if the decrease button is clicked, the value of the variable is decreased (as specified by value--).
* However, just changing the value of the variable isn't enough to make the screen change. For this reason, there is a special method called repaint() which automatically calls paint(Graphics g) again to redraw the screen. Note that the method repaint() does not take any parameters, not even a Graphics parameter!

Here is the updated applet, complete with the action() method:

The position of buttons on the screen

You will have noticed by now that we did not include any command to place the button at a certain position on the screen. The buttons simply appeared as close to the top of the applet as possible. Unfortunately, Java does not give you a way of specifying exactly where you want the buttons to appear on the screen - well, that's not entirely true. There are objects called frames and canvases, but they are horribly complex and definitely should be left until a later session.

For the moment, just get used to the fact that your buttons will appear at the top of the screen. They fill up the top "line" until there is no room for any more. Then they start to fill the next "line" down. The following applet is rather narrow (I declared the width of the applet to be 120). You will also note that I have displayed a message at position (10,10) and that it has been partially obscured by the buttons.

 Summary of Buttons

The following "skeleton" program gives the minimum amount of code necessary to run a button. Use it as a template and add as many buttons and as much code as you like:

import java.applet.*;
import java.awt.*;

public class button_skeleton extends Applet
{ Button b;

public void init ()
{ Button b = new Button("Button caption");
add(b);
}

public boolean action (Event e, Object args)
{ if (e.target == b)
{ // User has clicked on button 'b'
// so do something!
}
return true; // Yes, we do need this!
}
}

No comments:

Post a Comment

 
THANK YOU FOR VISITING