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.

有帮助吗?

解决方案

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...

其他提示

e.getSource().getClass().getName() returns the full name of the class of the button.

But why do you want it?

use getSource() method of ActionEvent in actionPerformed():

if(e.getSource() instanceof MyCustomButton ){

} else if(e.getSource() instanceof MyCustomButton1 ){

} else {

}

Try below code

if(e.getSource().getClass()==MyCustomButton.class) 

to make it more robust in place of

if(e.getSource().getClass().getName.equals("com.x.y.z.MyCustomButton")) 

Advantage:

  • if in future you change the package of class MyCustomButton then also it will work fine.
  • change in package is caught at compile time
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top