Results 1 to 3 of 3
  1. #1
    MW130 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    307
    Rep Power
    2

    Default question about action listeners

    Hey guys, I had a question. I want to make a simple GUI in swing (any good tutorials you guys know of?), and I know how to make an action for one button. However, how would you do if you have like 5 buttons and want to make an event for each :O? For example, you do
    Java Code:
    button1.addActionListener(this)
    and then you fill the method,
    Java Code:
    public void actionPerformed (ActionEvent e){
    }
    Anyway, how does the program know that the object "e" of the class ActionEvent is actually button1? How would you go about making events if you have more than one button? Thanks all!

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,450
    Rep Power
    19

    Default Re: question about action listeners

    Normally I would use an anonymous class:
    Java Code:
    button1.addActionListener(new ActionListener { ... fill in the actionPerformed method ... });
    If there's more than a couple of lines of code required then I would have the actionPerformed call a method on the enclosing class, otherwise it looks messy.
    Please do not ask for code as refusal often offends.

  3. #3
    monkeyjr97 is offline Senior Member
    Join Date
    Nov 2012
    Posts
    258
    Rep Power
    2

    Default Re: question about action listeners

    Also you can do:

    Java Code:
    public void actionPerformed (ActionEvent e){
    
    if(e.getSource() == testButton) {
    
    //do something
    
    }
    
    else if(e.getSource() == nextButton) {
    
    //do smething
    
    }
    
    }

Similar Threads

  1. Action/Change Listeners
    By Conor-Magee in forum New To Java
    Replies: 21
    Last Post: 11-20-2011, 03:21 AM
  2. action listeners
    By Ike in forum New To Java
    Replies: 13
    Last Post: 11-07-2011, 10:31 AM
  3. Adding Action Listeners
    By mamoonrizwan in forum Advanced Java
    Replies: 2
    Last Post: 08-07-2011, 06:25 PM
  4. Creating a GUI events with action listeners
    By sidd0123 in forum AWT / Swing
    Replies: 8
    Last Post: 04-02-2010, 11:32 PM
  5. Action Event and Listeners
    By lost1 in forum New To Java
    Replies: 3
    Last Post: 11-14-2007, 04: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
  •