gpt4 book ai didi

java - 如何从 java 中的 Action Listener 获取按钮 (JButton) 的类或类型?

转载 作者:行者123 更新时间:2023-12-02 06:03:17 25 4
gpt4 key购买 nike

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);
}
}

在上面的示例中,我有 2 个 JButton,一个是自定义的,第二个扩展了第一个。

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]

为了实现我的 Action 监听器,我从打印输出中知道java能够返回我按下的按钮的类,我该怎么做?

编辑1:我的目标是实现一个具有 2 类按钮的 gui,如果单击其中一个按钮,我就会对该类型的按钮执行一组操作,反之亦然,希望它能简化我的操作监听器实现。

最佳答案

ActionEvent 提供对触发事件的 的引用,在您的情况下,这将是 JButton

您可以通过将源与已知引用进行比较来简单地检查哪个按钮触发了事件,但利用按钮 actionCommand 属性会更简单...

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

这假设您设置了按钮 actionCommand 属性。

如果做不到这一点,你就看正文了......

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

就个人而言,这只是自找麻烦,因为您可能有多个具有相同名称的按钮。最好使用按钮 actionCommand 属性。

更好的解决方案是仅使用 actions API ,这是一个自包含的操作概念,它带有配置信息,那么你就不在乎...

关于java - 如何从 java 中的 Action Listener 获取按钮 (JButton) 的类或类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22500279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com