Results 1 to 14 of 14
  1. #1
    Ike
    Ike is offline Member
    Join Date
    Aug 2011
    Posts
    21
    Rep Power
    0

    Default action listeners

    I have two JButtons, and app is supposed to do one thing when button1 is pressed, and another thing when button2 is pressed.
    I already know how to do this with just one button, but have no idea how to create two handlers, for one button each like:

    go1.addActionListener(handler1);
    go2.addActionListener(handler2);

    There are some explanations out there, but they all use keyword 'this', so in general not much helpful, since I don't know what that means although I've been trying for months.
    So if anyone can explain this without using 'this' it would be very helpful.

  2. #2
    neptune692 is offline Member
    Join Date
    Jan 2011
    Posts
    20
    Rep Power
    0

    Default Re: action listeners

    This assigns an ActionListener to both buttons. When an action is performed check to see which button is the source of the event by using e.getSource().

    Java Code:
    import javax.swing.*;
    import java.awt.event.*;
    
    
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            new Main();
        }
        
        
        JButton button1 = new JButton("Button 1");
        JButton button2 = new JButton("Button 2");
        
        //Create an instance of your ActionListener
        ButtonActionListener buttonListener = new ButtonActionListener();
        
        public Main() {
            
            //add listener to buttons
            button1.addActionListener(buttonListener);
            button2.addActionListener(buttonListener);
            
            //or...
            //button1.addActionListener(new ButtonActionListener());
            //button2.addActionListener(new ButtonActionListener());
            
            
            
            
            //create a frame and position buttons in container...
            
        }
        
        
        class ButtonActionListener implements ActionListener {
            
            public void actionPerformed(ActionEvent e) {
                
                if(e.getSource()==button1) {
                    
                    //executed when button1 is pressed...
                }
                
                if(e.getSource()==button2) {
                    
                    //executed when button2 is pressed...
                }
            }
        }
        
    }

  3. #3
    Ike
    Ike is offline Member
    Join Date
    Aug 2011
    Posts
    21
    Rep Power
    0

    Default Re: action listeners

    Very nice, thanks.
    You could have saved some space by referring just to 'e.getSource' line, but this way it's complete for all future similar inquiries.

  4. #4
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,236
    Rep Power
    7

    Default Re: action listeners

    You should not be testing the button to determine which piece of code to execute.

    Insetead create 2 classes.

  5. #5
    neptune692 is offline Member
    Join Date
    Jan 2011
    Posts
    20
    Rep Power
    0

    Default Re: action listeners

    You don't need to create two separate classes implementing an ActionListener for each button? My understanding was you could use event.getSource() to determine the source of the event and execute the appropriate code with an if-statment. If you had twenty buttons that equals twenty separate classes implementing an ActionListener. That doesn't seem very efficient or reusable.

    Maybe I misunderstood... but even Oracle uses e.getSource() to redirect events based on which Component created the event.

    http://download.oracle.com/javase/tu...ts/button.html
    http://www.rgagnon.com/javadetails/java-0468.html
    Last edited by neptune692; 11-06-2011 at 05:25 AM.

  6. #6
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,236
    Rep Power
    7

    Default Re: action listeners

    Using "if statements" in a listener is not a good idea. Checking the source of the event is not a good idea.

    It is better to have separate listeners that each do a specific function.

    Actually, it is even better to use an Action so it can easily be shared between different component types (buttons, menu items). See: How to Use Actions (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: action listeners

    It depends. A lot of us use anonymous inner classes for this, classes that have no name and are created on the spot for whatever button needs the action.

  8. #8
    neptune692 is offline Member
    Join Date
    Jan 2011
    Posts
    20
    Rep Power
    0

    Default Re: action listeners

    I mean i've always been taught even in a lot of Java tutorial books that it was ok to use if-statements to redirect events inside the same class. If I had twenty buttons would I create a separate inner class for each one? It just seems that in some cases it would be more practical to create one class with if-statments inside them? Or did I learn this completely wrong xD.

  9. #9
    neptune692 is offline Member
    Join Date
    Jan 2011
    Posts
    20
    Rep Power
    0

    Default Re: action listeners

    Quote Originally Posted by camickr View Post
    Using "if statements" in a listener is not a good idea. Checking the source of the event is not a good idea.

    It is better to have separate listeners that each do a specific function.

    Actually, it is even better to use an Action so it can easily be shared between different component types (buttons, menu items). See: How to Use Actions (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)
    Oh but I see your point there, having an ActionListener that is responsible for a bunch of events isn't easily shared with other components that in the future may need to execute the same action.

  10. #10
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,236
    Rep Power
    7

    Default Re: action listeners

    If I had twenty buttons would I create a separate inner class for each one?
    If you have twenty buttons, then chances are each button has similiar logic in which case you can use a common ActionListener that still doesn't need to check which button was pressed.

    See: the ButtonCalculator example in this posting: Basic Calculator that shows one way to do this.

    I'm not saying "never" use if statements. However usually there is a better approach.
    Last edited by camickr; 11-06-2011 at 05:45 AM.

  11. #11
    neptune692 is offline Member
    Join Date
    Jan 2011
    Posts
    20
    Rep Power
    0

    Default Re: action listeners

    Ok thank you :) Its always nice to learn something new. I can see where it would be a better idea to create separate actions. I'll brush up on it.

  12. #12
    Cosmos is offline Member
    Join Date
    Jul 2011
    Location
    New Delhi,India
    Posts
    56
    Rep Power
    0

    Default Re: action listeners

    Quote Originally Posted by Ike View Post
    I have two JButtons, and app is supposed to do one thing when button1 is pressed, and another thing when button2 is pressed.
    I already know how to do this with just one button, but have no idea how to create two handlers, for one button each like:

    go1.addActionListener(handler1);
    go2.addActionListener(handler2);

    There are some explanations out there, but they all use keyword 'this', so in general not much helpful, since I don't know what that means although I've been trying for months.
    So if anyone can explain this without using 'this' it would be very helpful.
    i read that you have trouble in handling "this"....well maybe i can help you with that....

    we have to specify in addActionListener method that which class will be handling the action event......we specify it in the argument of addActionListener argument......in your case you want that it must be handled in class other then the class containing the button(where event will be generated)......so you specified the object of the class "handler" in the argument.......but if you want to handle the event in the same class that contains your button then u specify "this" in the argument list......by writing "this" in the argument list,it means that the action event will be handled in the same class that contains the button....

    maybe my post can clarify some of your doubts....

  13. #13
    Ike
    Ike is offline Member
    Join Date
    Aug 2011
    Posts
    21
    Rep Power
    0

    Default Re: action listeners

    Well, it didn't help me a bit. It was like reading Swahili :)
    I just can't grab the concept of 'this' anywhere in Java.
    Doesn't matter, I'll deal with that later. Thanx for your time.


    Anyway, neptune692'nd's :) solution works perfect for my case.
    I have couple complicated calculations to do on some data, and I just needed the trigger on what method to jump further.

  14. #14
    Cosmos is offline Member
    Join Date
    Jul 2011
    Location
    New Delhi,India
    Posts
    56
    Rep Power
    0

    Default Re: action listeners

    let me explain you thoroughly....

    1st according to your code(i.e without using the "this")-

    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;

    class MyButton implements ActionListener{

    MyButton(){
    }

    public void actionPerformed(ActionEvent ae){
    System.out.println("Button is clicked");
    }

    }

    public class MyApplet extends Applet{

    Button b;

    public void init(){
    b=new Button("Click");
    MyButton mb=new MyButton();
    b.addActionListener(mb);
    }


    }

    in this case,the event source,i.e. the button is in MyApplet class and it is handled in MyButton class.....so we pass the object of MyButton class to the argument of addActionListener method which specify that the button event will be handled in the class MyButton(and not in the class MyApplet)....
    we have implemented ActionListener in MyButton class and not in the MyApplet class,so we have to give the implementation of actionPerformed() method in the class MyButton....but as the program execution starts with MyApplet class,and event will be generated in MyApplet class itself(which is presently not implementing ActionListener),therefore we have to specify in addActionListener method as the name of the class that will be handling the ActionEvent generated by the Button b in MyApplet class,as in our example the MyButton class is handling the action event,so we specify the object of MyButton class in addActionListener method

    --------------------------

    in 2nd implementation(i.e.using "this")

    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;

    public class MyApplet extends Applet implements ActionListener{

    Button b;

    public void init(){
    b=new Button("Click");
    b.addActionListener(this);
    }

    public void actionPerformed(ActionEvent ae){
    System.out.println("button is clicked");
    }

    }

    in this implementation,we implemented "ActionListener" in the same class that contains the button object i.e.we implemented the ActionListener in the same class that will generate the event.....as we have implemented the ActionListener in the class MyApplet itself,we have to tell the compiler that button will be handled in the same class that contains the Button,therefore we specified "this" in the argument list of addActionListener method,which tells the compiler that the action event generated by the button will be handled in "this" class,i.e. the same class that contains the button...

Similar Threads

  1. Adding Action Listeners
    By mamoonrizwan in forum Advanced Java
    Replies: 2
    Last Post: 08-07-2011, 07:25 PM
  2. Applets issue with Action Listeners
    By aadem in forum New To Java
    Replies: 2
    Last Post: 03-19-2011, 07:17 PM
  3. Creating a GUI events with action listeners
    By sidd0123 in forum AWT / Swing
    Replies: 8
    Last Post: 04-03-2010, 12:32 AM
  4. JOptionPane, action listeners, and the Enter key.
    By DigitalMan in forum AWT / Swing
    Replies: 5
    Last Post: 01-26-2010, 03:51 AM
  5. Action Event and Listeners
    By lost1 in forum New To Java
    Replies: 3
    Last Post: 11-14-2007, 05:26 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •