[an error occurred while processing this directive]

Button Pressing Example


In the program code given below, the Frame contains three buttons named - "Bonjour", "Good Day", "Aurevoir". The purpose of these three buttons need to be preserved within a command associated with the button. That is a different action takes place on the click of each button.

You need to run this program outside the browser because this is an application. Moreover, if you don't to check that which button was selected then in that case you need to associate a different ActionListener to each button rather than associating one to all. 

The following program demonstrates the event generated by each button.

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")
    f.add(b = new Button("Good Day"), BorderLayout.CENTER)
    f.add(b = new Button("Aurevoir"), BorderLayout.SOUTH)

class MyActionListener implements ActionListener 
  public void actionPerformed(ActionEvent ae) {
    String s = ae.getActionCommand()
    if (s.equals("Exit")) { 
      else if (s.equals("Bonjour")) { 
        System.out.println("Good Morning")
          System.out.println(s + " clicked")

Output of the program:

C:\newprgrm>javac ButtonPressDemo.java

C:\newprgrm>java ButtonPressDemo
Good Morning clicked
Good Day clicked


Download this example.




[an error occurred while processing this directive]