繁体   English   中英

Swing awt 组件方法 getName from setName?

[英]Swing awt component method getName from setName?

尝试将getName()方法添加到基于此方法的setName() void java.awt.Component.setName(String arg0)但没有运气。 下面的按钮被加载到 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 中,但似乎没有适合 object 提取值的方法,因此我可以进行比较。 如果您要进行比较,这是定义“id”的最佳方法吗?

您的JButton定义代码应为:

button.setText("Binary");

您的ActionListener代码应该是:

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

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

基于 setName 或其他类似的东西

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

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

对于JButton ,您可以使用:

button.setActionCommand("Binary");

然后在您使用的ActionListener中:

String command = e.getActionCommand();

setName 值明确在 ActionEvent 中

不,不是。 ActionEvent 中包含对源 object 的引用。 需要先访问源码,才能访问源码object的方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM