Action Listener, Determing which button was pressed

Discussion in 'Java' started by Ben, Feb 11, 2006.

  1. Ben

    Ben Guest

    Hi,
    Could anyone help me with this problem. I have an action listener
    associated with a number of buttons. I can get the action listener to
    work, but what code do I need to findout which button was pressed.

    This is the layout of the action listener class.

    import java.awt.event.*;
    import java.awt.Component;

    public class ButtonListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {

    }

    }

    Thanks in advance.

    Ben.
     
    Ben, Feb 11, 2006
    #1
    1. Advertising

  2. Ben

    Chris Lamb Guest

    On 11 Feb 2006 14:02:14 -0800, Ben wrote:

    > Hi,
    > Could anyone help me with this problem. I have an action listener
    > associated with a number of buttons. I can get the action listener to
    > work, but what code do I need to findout which button was pressed.
    >
    > This is the layout of the action listener class.
    >
    > import java.awt.event.*;
    > import java.awt.Component;
    >
    > public class ButtonListener implements ActionListener
    > {
    > public void actionPerformed (ActionEvent e)
    > {
    >
    > }
    >
    > }
    >
    > Thanks in advance.
    >
    > Ben.


    Have you tried setActionCommand() method for the JButton? Then you can use
    e.getActionCommand() in your ActionListener to query it.

    Chris
     
    Chris Lamb, Feb 11, 2006
    #2
    1. Advertising

  3. Ben

    Chris Lamb Guest

    On Sun, 12 Feb 2006 00:14:30 +0000, Thomas Hawtin wrote:

    > Chris Lamb wrote:
    >> On 11 Feb 2006 14:02:14 -0800, Ben wrote:
    >>
    >>> Could anyone help me with this problem. I have an action listener
    >>> associated with a number of buttons. I can get the action listener to
    >>> work, but what code do I need to findout which button was pressed.
    >>>
    >>> This is the layout of the action listener class.
    >>>
    >>> import java.awt.event.*;
    >>> import java.awt.Component;
    >>>
    >>> public class ButtonListener implements ActionListener
    >>> {
    >>> public void actionPerformed (ActionEvent e)
    >>> {
    >>>
    >>> }
    >>>
    >>> }

    >>
    >> Have you tried setActionCommand() method for the JButton? Then you can use
    >> e.getActionCommand() in your ActionListener to query it.

    >
    > Or more directly, use e.getSource().
    >
    > It's usually better to create a new listener instance for each event source.


    Ah, yes indeedy. I'm afraid I must put my hand up and admit to using the
    'cheap 'n' nasty' on more occasions than is appropriate :).


    Chris
     
    Chris Lamb, Feb 12, 2006
    #3
  4. Chris Lamb wrote:
    > On 11 Feb 2006 14:02:14 -0800, Ben wrote:
    >
    >> Could anyone help me with this problem. I have an action listener
    >> associated with a number of buttons. I can get the action listener to
    >> work, but what code do I need to findout which button was pressed.
    >>
    >> This is the layout of the action listener class.
    >>
    >> import java.awt.event.*;
    >> import java.awt.Component;
    >>
    >> public class ButtonListener implements ActionListener
    >> {
    >> public void actionPerformed (ActionEvent e)
    >> {
    >>
    >> }
    >>
    >> }

    >
    > Have you tried setActionCommand() method for the JButton? Then you can use
    > e.getActionCommand() in your ActionListener to query it.


    Or more directly, use e.getSource().

    It's usually better to create a new listener instance for each event source.

    Tom Hawtin
    --
    Unemployed English Java programmer
    http://jroller.com/page/tackline/
     
    Thomas Hawtin, Feb 12, 2006
    #4
  5. Thomas Hawtin wrote:
    >>
    >> Have you tried setActionCommand() method for the JButton? Then you can
    >> use
    >> e.getActionCommand() in your ActionListener to query it.

    >
    > Or more directly, use e.getSource().
    >
    > It's usually better to create a new listener instance for each event
    > source.
    >
    > Tom Hawtin


    I don't know, for one or two buttons maybe. But if you have a bunch of
    menus and buttons I find it to be much less confusing to have all of the
    events go to the same listener and separate them out there.

    --

    Knute Johnson
    email s/nospam/knute/
     
    Knute Johnson, Feb 12, 2006
    #5
  6. Ben

    Guest

    Here here. Separate listeners for each button in many situations is
    stunningly inefficient and confusing.
     
    , Feb 12, 2006
    #6
  7. wrote:
    > Here here. Separate listeners for each button in many situations is
    > stunningly inefficient and confusing.


    Really?? Are you referring to class loading time? I would be surprised
    if that makes any significant difference in this day and age. I'm
    confused by the idea that it's confusing.

    Tom Hawtin
    --
    Unemployed English Java programmer
    http://jroller.com/page/tackline/
     
    Thomas Hawtin, Feb 12, 2006
    #7
  8. Thomas Hawtin wrote:
    > wrote:
    >> Here here. Separate listeners for each button in many situations is
    >> stunningly inefficient and confusing.

    >
    > Really?? Are you referring to class loading time? I would be surprised
    > if that makes any significant difference in this day and age. I'm
    > confused by the idea that it's confusing.
    >
    > Tom Hawtin


    You said better, I said less confusing, I think we both have
    preferences. It is my preference to group the event handling together
    if I have more than a couple of related events. I usually do that when
    I create a frame with a bunch of menus. I like the menu creation code
    together and the event processing code together. Less confusing for the
    unimaginative like me :).

    --

    Knute Johnson
    email s/nospam/knute/
     
    Knute Johnson, Feb 12, 2006
    #8
  9. Ben

    Roedy Green Guest

    On Sun, 12 Feb 2006 10:31:19 -0800, Knute Johnson
    <> wrote, quoted or indirectly quoted someone
    who said :

    >> Really?? Are you referring to class loading time? I would be surprised
    >> if that makes any significant difference in this day and age. I'm
    >> confused by the idea that it's confusing.


    each anonymous listener class adds about 3K overhead.
    --
    Canadian Mind Products, Roedy Green.
    http://mindprod.com Java custom programming, consulting and coaching.
     
    Roedy Green, Feb 13, 2006
    #9
  10. Ben

    Roedy Green Guest

    On Mon, 13 Feb 2006 15:58:52 +0000, Thomas Hawtin
    <> wrote, quoted or indirectly quoted someone
    who said :

    >> each anonymous listener class adds about 3K overhead.

    >
    >3K overhead to what?

    that is how much real ram they consume when they are sitting there
    fielding events.
    --
    Canadian Mind Products, Roedy Green.
    http://mindprod.com Java custom programming, consulting and coaching.
     
    Roedy Green, Feb 13, 2006
    #10
  11. Roedy Green wrote:
    > On Sun, 12 Feb 2006 10:31:19 -0800, Knute Johnson
    > <> wrote, quoted or indirectly quoted someone
    > who said :
    >
    >
    >>>Really?? Are you referring to class loading time? I would be surprised
    >>>if that makes any significant difference in this day and age. I'm
    >>>confused by the idea that it's confusing.

    >
    >
    > each anonymous listener class adds about 3K overhead.


    3K overhead to what?

    Class files each have string references to all packages, method names
    and signatures involved, which makes them larger than should be
    expected. Within JAR files they will normally be compressed.

    I have to confess a good deal of ignorance about runtime structures.
    Presumably you don't need all the copies of the same data. That should
    strip away most of the inefficiency.

    Tom Hawtin
    --
    Unemployed English Java programmer
    http://jroller.com/page/tackline/
     
    Thomas Hawtin, Feb 13, 2006
    #11
  12. Roedy Green wrote:
    > On Mon, 13 Feb 2006 15:58:52 +0000, Thomas Hawtin
    > <> wrote, quoted or indirectly quoted someone
    > who said :
    >
    >
    >>>each anonymous listener class adds about 3K overhead.

    >>
    >>3K overhead to what?

    >
    > that is how much real ram they consume when they are sitting there
    > fielding events.


    I couldn't believe it. So I consulted the google. And indeed the web
    does say 3K. It's even printed on like real paper, so it must be right.

    http://java.sun.com/docs/books/performance/1st_edition/html/JPClassLoading.fm.html#24833

    Okay, so perhaps it's the old school book trick wherein generations of
    authors copying other authors' mistakes. So I shall do my own testing.
    Below is a quick & dirty program to create simplistic scalable example
    code. And indeed going up to 1000 anonymous inner classes it takes 3K a
    class. Unbelievable.

    Going higher hit a problem with a laughable hash algorithm in javac. I
    patched that with the String code, and reduced my expectations to fit
    within the limits of the class file format. 3000 anonymous inner classes
    require less memory than just one!!

    ???

    Ah yes, the permanent generation is reluctant to have its garbage
    collected (the clue is in the name). One of the EJB servers (BEA?) had a
    problem running on Sun's JRE because it could throw OutOfMemoryError
    despite having plenty of memory available.Apparently, it used to be the
    case that running out of memory for the permanent generation didn't
    trigger gc, so you need create transient data to force a collection
    (proper details are on the Bug Parade somewhere).

    In today's world, System.gc does not appear to collect from the
    permanent generation. Naive memory measurements are therefore misleading.


    The folk wisdom that inner classes are really expensive is hogwash.


    Still, it seems inefficient of the JVM to allocate permanent generation
    memory in such a manner.

    Tom Hawtin


    import java.io.*;

    class Gen {
    public static void main(String[] args) throws IOException {
    final int inners = Integer.getInteger("inners");
    File dir = new File("test"+inners);
    if (!dir.mkdir()) {
    throw new Error("mkdir: "+dir);
    }
    String pkg = "mylongpackagenameandsomerandompadding";
    File pkgDir = new File(dir, pkg);
    if (!pkgDir.mkdir()) {
    throw new Error("mkdir: "+pkgDir);
    }
    String cls = "Test"+inners;
    Writer out = new BufferedWriter(new FileWriter(new File(
    pkgDir, cls+".java"
    )));

    out.write(
    "package "+pkg+";\n"
    +"\n"
    +"import java.awt.*;\n"
    +"import java.awt.event.*;\n"
    +"import javax.swing.*;\n"
    +"\n"
    +"class "+cls+" {\n"
    +" public static void main(String[] args) throws Exception {\n"
    +" final JButton button = new JButton();\n"
    +"\n"
    );
    for (int ct=0; ct<inners; ++ct) {
    out.write(
    " button.addActionListener(new ActionListener() {\n"
    +" public void actionPerformed(ActionEvent event) {\n"
    +" button.setText(\""+ct+"\");\n"
    +" }\n"
    +" });\n"
    );
    }
    out.write(
    "\n"
    +" System.gc();\n"
    +" Runtime runtime = Runtime.getRuntime();\n"
    +" System.out.println(\n"
    +" \""+inners+" - \"+\n"
    +" \"freeMemory: \" +runtime.freeMemory() +\", \"+\n"
    +" \"maxMemory: \" +runtime.maxMemory() +\", \"+\n"
    +" \"totalMemory: \"+runtime.totalMemory()+\", \"\n"
    +" );\n"
    +" Thread.currentThread().join();\n"
    +" }\n"
    +"}\n"
    );
    out.close();
    }
    }
    --
    Unemployed English Java programmer
    http://jroller.com/page/tackline/
     
    Thomas Hawtin, Feb 13, 2006
    #12
  13. Thomas Hawtin wrote:
    >
    > In today's world, System.gc does not appear to collect from the
    > permanent generation. Naive memory measurements are therefore misleading.


    Playing around with it some more, seems I want to be measuring non-heap
    memory. I get around 1K or so per anonymous inner class with -server. I
    shall play some more.

    Tom Hawtin
    --
    Unemployed English Java programmer
    http://jroller.com/page/tackline/
     
    Thomas Hawtin, Feb 14, 2006
    #13
  14. Ben

    Roedy Green Guest

    On Mon, 13 Feb 2006 23:02:10 +0000, Thomas Hawtin
    <> wrote, quoted or indirectly quoted someone
    who said :

    > And indeed go


    then on top of that you might have multiple instances of those
    classes.
    --
    Canadian Mind Products, Roedy Green.
    http://mindprod.com Java custom programming, consulting and coaching.
     
    Roedy Green, Feb 14, 2006
    #14
  15. Ben

    Chris Uppal Guest

    Thomas Hawtin wrote:

    > Going higher hit a problem with a laughable hash algorithm in javac.


    ?

    Details, please ;-)

    -- chris
     
    Chris Uppal, Feb 14, 2006
    #15
  16. Chris Uppal wrote:
    > Thomas Hawtin wrote:
    >
    >
    >>Going higher hit a problem with a laughable hash algorithm in javac.

    >
    >
    > ?
    >
    > Details, please ;-)


    For lengths greater than zero:

    len * (41 * 41 * 41) +
    cs[start] * (41 * 41) +
    cs[start + len - 1] * 41 +
    cs[start + (len >> 1)]

    So it's based on the length, first character, last character and middle
    character. I had class names like Test1000, Test1010,, Test1020, etc.
    Not good. Even the JDK 1.02 String hashCode was better than that.
    Sampling does not pay when it come to hash codes.

    The patched version seemed to run much faster. It actually completed
    before being killed.

    Tom Hawtin
    --
    Unemployed English Java programmer
    http://jroller.com/page/tackline/
     
    Thomas Hawtin, Feb 14, 2006
    #16
  17. Ben

    steve Guest

    On Sun, 12 Feb 2006 06:02:14 +0800, Ben wrote
    (in article <>):

    > Hi,
    > Could anyone help me with this problem. I have an action listener
    > associated with a number of buttons. I can get the action listener to
    > work, but what code do I need to findout which button was pressed.
    >
    > This is the layout of the action listener class.
    >
    > import java.awt.event.*;
    > import java.awt.Component;
    >
    > public class ButtonListener implements ActionListener
    > {
    > public void actionPerformed (ActionEvent e)
    > {
    >
    > }
    >
    > }
    >
    > Thanks in advance.
    >
    > Ben.
    >



    something like this

    public class ShipmentsCard1 extends JPanel implements ActionListener {

    Quit_BUTT.setText("Quit");
    Quit_BUTT.setBounds(new Rectangle(615, 10, 90, 25));
    Quit_BUTT.setFont(new Font("Arial", 0, 9));
    Reports_BUTT.setText("Reports");
    Reports_BUTT.setBounds(new Rectangle(501, 10, 110, 25));
    Reports_BUTT.setFont(new Font("Arial", 0, 9));


    Quit_BUTT.addActionListener(this);
    Reports_BUTT.addActionListener(this);



    public void actionPerformed(ActionEvent evt) {
    Object source = evt.getSource();

    if (source == Quit_BUTT) {
    Killprogram();
    }

    if (source == Reports_BUTT) {
    //this is working (21/12/2005)
    printRecords();
    }

    }

    }

    where possible keep it all together in 1 routine, adding listener classes all
    over the place as separate items makes code maintanance a PIG.
     
    steve, Feb 14, 2006
    #17
  18. Ben

    IchBin Guest

    steve wrote:
    > On Sun, 12 Feb 2006 06:02:14 +0800, Ben wrote
    > (in article <>):
    >
    >> Hi,
    >> Could anyone help me with this problem. I have an action listener
    >> associated with a number of buttons. I can get the action listener to
    >> work, but what code do I need to findout which button was pressed.
    >>


    [snip code]

    If I implement ActionListener. I usually do it this way:

    public class ShipmentsCard1 extends JPanel implements ActionListener {
    private final String QUIT = "Quit";
    private final String REPORT = "Reports";

    Quit_BUTT.setText(QUIT);
    Quit_BUTT.setBounds(new Rectangle(615, 10, 90, 25));
    Quit_BUTT.setFont(new Font("Arial", 0, 9));
    Quit_BUTT.setActionCommand(QUIT);
    Quit_BUTT.addActionListener(this);

    Reports_BUTT.setText(REPORT);
    Reports_BUTT.setBounds(new Rectangle(501, 10, 110, 25));
    Reports_BUTT.setFont(new Font("Arial", 0, 9));
    Reports_BUTT.setActionCommand(REPORT);
    Reports_BUTT.addActionListener(this);
     
    IchBin, Feb 15, 2006
    #18
  19. Ben

    Chris Uppal Guest

    Thomas Hawtin wrote:

    > So it's based on the length, first character, last character and middle
    > character.


    Dear Gods!


    > The patched version seemed to run much faster. It actually completed
    > before being killed.


    Dunno what you're complaining about -- even with 3000 inner classes it still
    compiled in only a little over two minutes ;-)

    -- chris
     
    Chris Uppal, Feb 15, 2006
    #19
  20. Ben

    Chris Uppal Guest

    Thomas Hawtin wrote:

    > Playing around with it some more, seems I want to be measuring non-heap
    > memory. I get around 1K or so per anonymous inner class with -server. I
    > shall play some more.


    I get the same using the 1.5 client VM. Each inner seems to add around 1.1K or
    1.2K to the what jconsole/JMX calls the "Perm Gen" memory pool. (I haven't
    been able to find any info relating the "Perm Gen" to the "Perm Gen [shared
    ro]" and "Perm Gen [shared rw]" pools.)

    They add some load to the code-cache too, but that's to be expected since there
    are actually more methods... Presuming that the choice is between putting a
    fixed amount of code in either an dedicated inner class or somewhere else, I
    don't think the code size is relevant. Sadly the monitoring doesn't seem to
    work with -Xint.

    Other than that, they don't seem to add any load to reported memory use.

    -- chris
     
    Chris Uppal, Feb 15, 2006
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?Utf-8?B?RXJpYyBOZWxzb24=?=

    Which button pressed?

    =?Utf-8?B?RXJpYyBOZWxzb24=?=, Sep 23, 2004, in forum: ASP .Net
    Replies:
    7
    Views:
    2,453
  2. Keith Patrick

    Determining which Button was pressed

    Keith Patrick, Feb 22, 2005, in forum: ASP .Net
    Replies:
    4
    Views:
    3,404
    Keith Patrick
    Feb 22, 2005
  3. Jonathan Crawford

    finding which button is pressed

    Jonathan Crawford, Jan 24, 2006, in forum: ASP .Net
    Replies:
    5
    Views:
    481
    slagomite
    Jan 24, 2006
  4. Rune
    Replies:
    6
    Views:
    1,276
    Richie Hindle
    Jan 29, 2004
  5. Replies:
    1
    Views:
    161
Loading...

Share This Page