Home Java Example Java Awt Button Pressing Example
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Button Pressing Example

Advertisement
In the program code given below, the Frame contains three buttons named - "Bonjour", "Good Day", "Aurevoir".

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")
  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 of the program:

C:\newprgrm>javac ButtonPressDemo.java

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

C:\newprgrm>

Download this example.

 

 

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 18, 2008

Ask Questions?    Discuss: Button Pressing Example   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Codex
August 16, 2011
Java jbuttons

hello
thanigaivel
January 22, 2013
java

i want example program for java frames ..., buttons,check box..,events etc...
sagar kulkarni
February 10, 2012
Adding image to Button click Event

i want to add image to button click event how i can construct a progarm in simple way.
Ela
March 11, 2012
..

this code helps..thank you..!
Sabbir Jaman
July 25, 2013
Greetings

This example is very Fine I like is very Much
DMCA.com