如何从java中的动作侦听器获取按钮(JButton)的类或类型?
在上面的示例中,我有两个JButton,一个是自定义的,第二个扩展了第一个如何从java中的动作侦听器获取按钮(JButton)的类或类型?,java,swing,awt,paintcomponent,Java,Swing,Awt,Paintcomponent,在上面的示例中,我有两个JButton,一个是自定义的,第二个扩展了第一个 private class MyCustomButton extends JButton{...} private class MyCustomButton2 extends MyCustomButton{...} public class Example1 extends JPanel{ Example1{ MyCustomButton b1=new MyCustomButton("0"); My
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);
}
}
为了实现我的动作监听器,我从打印输出中知道java能够返回我按下的按钮的类,我该怎么做
编辑1:
我的目标是实现一个包含两类按钮的gui,如果单击其中一类按钮,我将为该类型的按钮提供一组操作,反之亦然,希望它将简化我的操作侦听器实现 e.getSource().getClass().getName()
返回按钮类的全名
但是您为什么想要它呢?在actionPerformed()
中使用getSource()的ActionEvent
方法:
ActionEvent
提供了对触发事件的源的引用,在您的情况下,这将是JButton
通过将源代码与已知引用进行比较,您可以简单地检查触发事件的按钮,但使用按钮actionCommand
properties会更简单
if(e.getSource() instanceof MyCustomButton ){
} else if(e.getSource() instanceof MyCustomButton1 ){
} else {
}
这假设您设置了按钮actionCommand
属性
如果没有做到这一点,你就只能继续写下去了
if ("name of action".equals(source.getActionCommand())) {...
就个人而言,这只是自找麻烦,因为您可能有多个按钮具有相同的名称。最好使用按钮actionCommand
属性
一个更好的解决方案是只使用,这是一个包含配置信息的操作的自包含概念,然后您就不在乎了…尝试下面的代码
JButton btn = (JButton)e.getSource();
if ("0".equals(btn.getText()) {...
使其更健壮,以代替
if(e.getSource().getClass()==MyCustomButton.class)
优点:
- 如果将来您更改class
MyCustomButton
的包,那么它也可以正常工作
- 在编译时捕获包中的更改
你应该考虑使用,依赖于类类型是错误的…无关:不扩展JSomething的任何一个,它们是为使用而设计的。
if(e.getSource().getClass()==MyCustomButton.class)
if(e.getSource().getClass().getName.equals("com.x.y.z.MyCustomButton"))