@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == thirdBtn) {
//System.out.println("Third Button Click");
System.out.println(e.getSource()+" Click");
}
}
在上面的代码中,我想知道是否不这样做:
//System.out.println("Third Button Click");
如果我能做这样的事情:
System.out.println(e.getSource()+" Click");
但是代码输出:
BlackJack.OverBoard$BlackJackButton[,440,395,100x25,alignmentX=0.0,alignmentY=0.5,
border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@7a3d8738,
flags=16777504,maximumSize=,minimumSize=,preferredSize=,
defaultIcon=,disabledIcon=,disabledSelectedIcon=,
margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],
paintBorder=false,paintFocus=true,
pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,
text=Change,defaultCapable=true] Click
我不想要这个,我想知道如何获取 JButton
名称并在点击时输出它。
编辑:
有些人很困惑。当我说“名称”(也许这个词用错了)时,我的意思是说你初始化了一个 JButton
JButton btnExample = new JButton();
我希望当您单击按钮时,它会在控制台中输出 btnExample
。
最佳答案
如果您知道只有 JComponent 才是 e.getSource()
的返回值,则可以强制转换为 JComponent。我使用 JComponent
作为强制转换,因为它提供更多的灵 active 。如果您仅使用 JButtons
,则可以安全地转换为 JButton
。
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == thirdBtn) {
//System.out.println("Third Button Click");
System.out.println(((JComponent) e.getSource()).getName()+" Click");
}
}
您可以根据您的具体需求,将 getName()
替换为 getText()
。
此外,==
运算符只能用于比较对象引用,因此请考虑从一开始就转换为 JComponent 并在名称上使用 .equals()
或文字。
编辑 您无法输出变量的名称,但可以设置 JComponent 的名称/文本。 例如
JButton btnExample = new JButton();
btnExample.setName("btnExample");
或者,如果您希望“btnExample”实际显示在按钮上:
JButton btnExample = new JButton();
btnExample.setText("btnExample");
关于java - 单击时获取 JButton 的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14310331/