Monday, 3 March 2014

AWT CONTROLS IN JAVA:BUTTONS

AWT BUTTON Class

Create AWT Buttons with simple Example..........

The java.awt package comes with many GUI components of which Button is the most important and most frequently used. A button functionality (what for it is) can be known by its label like OK or Cancel etc. A mouse click on the button generates an action.

Following is the class signature

public class Button extends Component implements Accessible

Any GUI component with event handling can be broadly divided into 8 steps.

  • Import java.awt and java.awt.event packages
  • Extending frame or applet and implementing appropriate listener interface that can handle    the events of the component successfully.
  • Set the layout.
  • Create components
  • Register or link the component with the listener interface
  • Beautification of the components (optional)
  • Adding the components to the frame or applet
  • Override all the abstract methods of the listener interface

By using the above 8 steps, let us develop a simple button program with 4 buttons with labels RED, GREEN, BLUE and CLOSE. The action is, the background of the frame should change as per the button clicked. When CLOSE is clicked, the frame should close.

EXAMPLE:

import java.awt.*; 
import java.awt.event.*; 
public class ButtonPressDemo { 
  public static void main(String[] args){ 
  Button b; 
  ActionListener a = new MyActionListener(); 
  Frame f = new Frame("Java Applet"); 
  f.add(b = new Button("Bonjour"), BorderLayout.NORTH); 
  b.setActionCommand("Good Morning"); 
  b.addActionListener(a); 
  f.add(b = new Button("Good Day"), BorderLayout.CENTER); 
  b.addActionListener(a); 
  f.add(b = new Button("Aurevoir"), BorderLayout.SOUTH); 
  b.setActionCommand("Exit"); 
  b.addActionListener(a); 
  f.pack(); 
  f.show(); 
  } 
class MyActionListener implements ActionListener { 
  public void actionPerformed(ActionEvent ae) {
  String s = ae.getActionCommand(); 
  if (s.equals("Exit")) { 
  System.exit(0); 
  } 
  else if (s.equals("Bonjour")) { 
  System.out.println("Good Morning"); 
  } 
  else { 
  System.out.println(s + " clicked"); 
  } 
  } 

OUTPUT:








No comments:

Post a Comment