1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
/* Set Action Command For AWT Button Example This java example shows how to set custom action command for AWT button using setActionCommand method of Java AWT Button class. */ import java.applet.Applet; import java.awt.Button; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /* <applet code="ButtonSetActionCommandExample" width=200 height=200> </applet> */ public class ButtonSetActionCommandExample extends Applet implements ActionListener{ String actionMessage=""; public void init(){ //create Button Button Button1 = new Button("I agree with the terms and conditions"); //add Button add(Button1); //set action listeners for buttons Button1.addActionListener(this); /* * By default, button's action command is it's label. But in * some cases, labels are too long and is not appropriate to use * it as an action command. In such situation you would want to * define custom short action command for a button. * * To set custom action command for a button, use * void setActionCommand(String command) * method of AWT Button class. */ Button1.setActionCommand("Agree"); } public void paint(Graphics g){ g.drawString(actionMessage,10,50); } public void actionPerformed(ActionEvent ae){ /* * Get the action command using * String getActionCommand() method. */ String action = ae.getActionCommand(); actionMessage = action + " button pressed!"; repaint(); } } |
Example Output
import java.awt.*;
import java.awt.event.*;
public class sri extends Frame implements ActionListener
{
public Button b,b1;
sri()
{
Button b=new Button(“India”);
Button b1=new Button(“Pakistan”);
add(b);
add(b1);
setVisible(true);
setBounds(0,0,1024,768);
b.addActionListener(this);
b1.addActionListener(this);
setLayout(null);
b.setBounds(100,200,100,20);
b1.setBounds(100,20,110,20);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent ee)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if(b==e.getSource())
{
System.out.println(“Hello”);
}
else if(e.getSource()==b1)
{
System.out.println(“hi”);
}
}
public static void main(String args[])
{
sri s=new sri();
}
}
What is wrong with this code