Creating Buttons in an Applet Window using Advanced Java Programming

Home  »  Java  »  Advance Java »    Java AWT (Abstract Window ToolKit) »    Buttons

Buttons are simple GUI components that trigger some action in the interface when they are pressed. For example a calculator applet might have buttons for each number and operator, or a dialog box might have buttons for OK and Cancel. In general a Button may be defined as a UI component that, when "pressed", triggers some action.

To create a button, use one of the following constructors:

Button)() creates an empty button with no label
Button(String) creates a button with the given string as its label.

After a Button is created one can get the value of the Button's label by using the getLabel() method and set the label using the setLabel(String) method.

Syntax:

Button btnName=new Button("Button Name");
add(btnName);

The first statement creates an object of the Button class and passes 'Button Name' as a parameter to the constructor.
The second statement adds the component on the applet using the add() method.

The following example creates four buttons and adds them to an applet. They are Rewind, Play, Fast Forward and Stop:

The above code will be stored in the file called ButtonTest.java, which on compilation will crate a class file called Button.class. Now compiple this file using below commands in the DOS mode:

C:\>jdk1.4\bin>javac ButtonTest.java
C:\>jdk1.4\bin>appletviewer ButtonTest.java


"Output of ButtonTest.java"


Download Complete Program

  -  



Methods of the Button Object:

Methods
Action
getLabel()Returns a string, which is the label of the Button.
setLabel(String)Adds or Changes the label on the Button.



AWT Controls



Label Buttons Check Boxes Radio Buttons
Choice Controls TextFields & Password TextAreas Scrolling Lists Scrollbars




No comments:

Post a Comment