单击获取JButton的名称 [英] Getting the name of a JButton on click
问题描述
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == thirdBtn) {
//System.out.println("Third Button Click");
System.out.println(e.getSource()+" Click");
}
}
在上面的代码中,我想知道是否要这样做:
In the code above, I was wondering if instead of doing this:
//System.out.println("Third Button Click");
如果我可以做这样的事情:
if I could do something like this:
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
名称并在点击时输出它.
I don't want this, I want to know how to get the JButton
name and output it on click.
有些人感到困惑.当我说名称"(也许是错误的词)时,我的意思是说您初始化了JButton
Some people are confused. When I say "name" (maybe that's the wrong word for it), I meant say you initialize a JButton
JButton btnExample = new JButton();
我想要它,以便当您单击按钮时,它会在控制台中输出btnExample
.
I want it so that when you click the button, it outputs btnExample
in the console.
推荐答案
如果知道只有JComponents将是e.getSource()
的返回值,则可以强制转换为JComponent.提供更大的灵活性.如果仅使用JButtons
,则可以安全地强制转换为JButton
.
You can cast to a JComponent if you know that only JComponents will be the return value of e.getSource()
I'm using JComponent
as the cast since it gives more flexibility. If you're only using JButtons
, you can safely cast to a JButton
instead.
@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()
.
Feel free to replace getName()
with getText()
, depending on what exactly you need.
此外,==
运算符仅应用于比较对象引用,因此请考虑从一开始就强制转换为JComponent并在名称或文本上使用.equals()
.
Also, the ==
operator should only be used to compare Object references, so consider casting to a JComponent from the beginning and using .equals()
on the names or text.
修改 您无法输出变量的名称,但是可以设置JComponent的名称/文本. 例如
Edit You can't output the name of the variable, but you can set the name/text of the JComponent. Eg
JButton btnExample = new JButton();
btnExample.setName("btnExample");
或者如果您希望"btnExample"实际上显示在按钮上:
Or if you want "btnExample" to actually be displayed on the button:
JButton btnExample = new JButton();
btnExample.setText("btnExample");
这篇关于单击获取JButton的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!