【发布时间】: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”的最佳方法吗?
【问题讨论】:
-
1)
JButton从Component继承getName()。 2) 见What is the XY problem? 3) 如欲获得更好的帮助,请edit 添加minimal reproducible example 或Short, Self Contained, Correct Example。