Search code examples
javaswingawtpaintcomponent

How to get the Class or Type of a button (JButton) in java from its Action Listener?


private class MyCustomButton extends JButton{...}
private class MyCustomButton2 extends MyCustomButton{...}

public class Example1 extends JPanel{
  Example1{
    MyCustomButton b1=new MyCustomButton("0");
    MyCustomButton2 b2=new MyCustomButton1("b2");
  }
  private class ButtonListener implements ActionListener//, KeyListener
  {
    public void actionPerformed(ActionEvent e)
    {
       System.out.println(e);
    }
}

In the example above I have 2 JButton, one a custom, and the second extends the first.

java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=0,when=1395217216471,modifiers=Button1] on **Example1.MyCustomButton**[,165,0,55x55,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.synth.SynthBorder@8a13863,flags=16777504,maximumSize=,minimumSize=,preferredSize=,defaultIcon=pressed.png,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=0,defaultCapable=true]

To implement my action listener, I know from the printout java is capable of returning the class of the button I pressed, how do I do that?

Edit 1: My goal is to implement a gui that has 2 classes of button, if one is clicked I have a set of actions for that type of button, vice versa, with the hope it will simplify my action listener implementation.


Solution

  • ActionEvent provides a reference to the source that triggered the event, in you case this would the JButton.

    You could simply check which button triggered the event by comparing the source with a known reference, but it would be simpler to utilise the buttons actionCommand properties...

    if ("name of action".equals(source.getActionCommand())) {...
    

    This assumes that you set the buttons actionCommand property.

    Failing that, your down to the text...

    JButton btn = (JButton)e.getSource();
    if ("0".equals(btn.getText()) {...
    

    Personally, that's just asking for trouble, as you might have multiple buttons with the same name. Better to use the buttons actionCommand property.

    A better solution would be to just use the actions API, which is self contained concept of an action which carries with it configuration information, then you don't care...