Java's Basic User Interface Components - The Button Class
(Page 3 of 10 )
We will start with the simplest of UI components: the button. Buttons are used to trigger events in a GUI environment (we have discussed Event Handling in detail in the previous tutorials). They are easy to manage and, most importantly, they are easy to use. The Button class is used to create buttons. When you add components to the container, you don’t specify a set of coordinates that indicates where the components are to be placed. The arrangement of components is handled by a layout manager in effect for the container. The default layout for a container is flow layout. Now let us write a simple code to test our button class.
To create a button use, one of the following constructors:
- Button() creates a button with no text label.
- Button(String) creates a button with the given string as label.
Example 1
/*
<Applet code= “ButtonTest.class”
Width = 500
Height = 100>
</applet>
*/
Import java.awt.*;
Public class ButtonTest extends java.applet.Applet
{
Button b1 = new Button (“Play”);
Button b2 = new Button (“Stop”);
Public void init(){
add(b1);
add(b2);
}
}
The following Java application illustrates addition of button controls to a panel.
Example 2
Import java.awt.*;
Public class ButttonTest2 extends Frame
{
Public static void main (String arg[])
{
Frame frm;
Panel panel,
Button b1, b2,
frm= new Frame(“Using Frame As Container For-Button Test”);
frm.setSize(300,400);
frm.setBackground (Color.green);
frm.setVisible(true)
panel = new Panel();
b1 = new Button(“Accept”);
b2 = new Button(“Cancel”);
frm.add(panel);
panel.add(b1);
panel.add(b2);
}
}
We can use the setLabel( ) method to change the label of the button and the getLabel( ) method to retrieve the caption.
Next: The Label Class >>
More Java Articles
More By Gayathri Gokul