Thursday 14 May 2015

Buttons in Java

Java buttons are just like the buttons in every other GUI. They are text surrounded by a shape, and they generate an ACTION_EVENT event-the argument is a button's label-after the user clicks them. Java uses the native operating system-Mac, Windows, UNIX, and so on-to actually draw the buttons, so the look and feel of the buttons will be what is expected by users on each platform. Listing 17.17 shows a simple example of using buttons;

Listing 17.17. Using buttons.
import java.awt.*;
import java.applet.Applet;


public class buttons extends Applet{
    Button a_button;

    public void init()
    {
        //make a new button called "Howdy"
        a_button = new Button("Howdy!");
        //add the button to the Applet, which extends Panel
        add(a_button);
    }
    public boolean action (Event e, Object o) {
        Dimension  d_should;
        if (e.target instanceof Button) {
            //check the button label and toggle between the two values
            if (((String)o).equals("Howdy!")) {
                a_button.setLabel("Alien Space Monster!");
            } else {
                a_button.setLabel("Howdy!");
            }
            //mark the button as having changed
            a_button.invalidate();
            //tell the applet to validate the layout
            validate();
        }
        return true;
    }
}


This applet starts out with a single button and then toggles the name of the button between two values every time the button is clicked.

  Notice how the invalidate method, inherited from Component, is used to mark the button as having changed in a way that would affect the layout. That isn't sufficient to force the applet to automatically lay out the screen again, although it ensures that the next time the screen is redrawn, things will look okay, so you have to invoke the validate method, inherited from Component, on the applet.
The available button creator calls and the key button methods follow.
new Button()

Creates a button with no label

new Button(String the_button_label)
Creates a button with the specified label.
setLabel(String the_new_label)
Sets the button label to the specified string.
String getLabel()
Returns the current button label as a string.  

No comments:

Post a Comment