What is meant by action command? How it can be used? Explain with example .
USING ACTION COMMANDS
Java allows us to associate commands with events caused by AWT buttons and menu items. In the case of buttons, commands are captions of buttons by default. But using captions as commands is not a good idea because when our program changes captions that appear in UI, we also need to change event handlers. We change this default command by using setAction Command() method. We can get commands for buttons and menu items by using the method getAction Command(). Another benefit of using action commands is that we can associate multiple components that are supposed to perform same action with the same command.
Example
import javax.swing.*;
import java.awt.event.*;
class EventDemo extends JFrame implements ActionListener
{
JLabel lb;
EventDemo ()
{
lb-new JLabel();
lb.setBounds (60,50,170,20);
set Layout(null);
JButton b1-new JButton("continue"); b1.setBounds (50, 120, 80,30); JButton b2=new JButton("Ok"); b2.setBounds (140, 120,80,30);
add(lb);
add (b1);
add (b2);
bl.addActionListener(this);
b2.addActionListener(this);
bl.setAction Command ("proceed"); b2.setAction Command ("proceed"); setSize(300, 300);
setVisible (true);
}
public void action Performed (Action Event e)
{
if(e.getAction Command ()=="proceed") lb.setText("Do you want to proceed???");
}
public static void main(String args[])
{
new Event Demo();
}
}
Now if we click on any of the buttons, they respond in same way because both buttons are set to same action command. Output looks like below:
Comments
Post a Comment