【问题标题】:Swing awt component method getName from setName?从setName摆动awt组件方法getName?
【发布时间】:2021-04-10 16:17:08
【问题描述】:

尝试基于此方法void java.awt.Component.setName(String arg0)getName() 方法添加到setName() 但没有运气。下面的按钮被加载到 contentPane 中。

我需要为在此方法中实例化的按钮添加一个动作监听器(基于 setName 或其他类似的东西):

public JButton JButtonComponent(String btnRef) {
    
    button = new JButton("Convert to binary");
    button.setMaximumSize(new Dimension(width/4,unitHeight));
    
    button.addActionListener(this);
    button.setName("Binary"); // my set name 
    
    return button;
}

这是我的 actionPerformed 方法:

@Override
public void actionPerformed(ActionEvent e) {

    System.out.println(e.getSource());

}

以及上述系统打印输出:

javax.swing.JButton[Binary,270,14,90x33,alignmentX=0.0,alignmentY=0.5,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=Convert,defaultCapable=true]

我的问题是如何从 ActionEvent 中获取我在 JButtonComponent 中定义的名称值? - setName 值显然在 ActionEvent e 中,但似乎没有适合对象提取值的方法,因此我可以进行比较。 如果您要进行比较,这是像在 HTML 中那样定义“id”的最佳方法吗?

【问题讨论】:

标签: java swing


【解决方案1】:

您的JButton 定义代码应为:

button.setText("Binary");

您的ActionListener 代码应该是:

JButton button = (JButton) event.getSource();
String text = button.getText();

您也可以使用JButton ActionCommand String 来传递附加信息;信息。

【讨论】:

    【解决方案2】:

    基于 setName 或其他类似的东西

    不要将 getName/setName 用于这样的事情。

    已经有一个 API 允许您使用“动作命令”。

    对于JButton,您可以使用:

    button.setActionCommand("Binary");
    

    然后在ActionListener你使用:

    String command = e.getActionCommand();
    

    setName 值在 ActionEvent 中很明显

    不,不是。对源对象的引用包含在 ActionEvent 中。您需要先访问源,然后才能访问源对象的方法:

    JButton button = (JButton)e.getSource();
    System.out.println( button.getName() );
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多