I am interested to get ActionEvent generated by multiple components from another class... please help. Example is given below.

class MyFrame {
    public MyFrame() {
    JFrame window = new JFrame();
    Container c = window.getContentPane();
    c.setLayout(new BorderLayout());

    JButton btn1 = new JButton("Save");
    JButton btn2 = new JButton("Delete");
    c.add(btn1);
    c.add(btn2);
    EventHandler handler = new EventHandler();
    btn1.addActionListener(handler);
    btn2.addActionListener(handler);

    .................

    }
}
class EventHandler implements ActionListener {
    public void actionPerformed(ActionEvent ae)
    {
        // what can i do here to get Event and also recognized which component fired event?
        // I have used getSource(). but problem is not solved.
        if ( ae.getSource() == btnSave)
        {
        }
    }
}

please help me as soon as possible... 

Recommended Answers

All 3 Replies

Youhave the Event - it's the parameter in actionPerformed. That gives you the source component. You can then test the attributes of that component (eg its actionCommand) to see which component it is. Eg
if ( ae.getSource().getActionCommand().equals("Save"))...

Dear James,
thanks for your reply, but still I'm getting an error like that
"Cannot Find Symbol"
if(ae.getSource().getActionCommand.equals("Save"))
Error highlight getActionCommand

getActionCommand sounds like the name of a method. you'll need () after that, basic Java syntax.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.