使用动作侦听器获取JButton的文本 [英] Get the text of a JButton using a Action Listener
本文介绍了使用动作侦听器获取JButton的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
getText
是否有原因导致错误:无法在代码所示的动作侦听器内找到符号
的原因?另外,如果存在,我该如何解决该错误?
Is there a reason why getText
causes an error: cannot find symbol
inside the action listener shown in the code? Also if there is, how would I fix this error?
class openNewPaneActionListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
String butSrcTxt = e.getSource().getText();
}
}
推荐答案
有
@Override
public void actionPerformed(ActionEvent e)
{
String butSrcTxt = e.getActionCommand();
}
如果您未指定 actionCommand
作为按钮,则改为使用按钮的文本
。
If you do not specify the actionCommand
for a button, then the text
of the button is used instead.
现在,如果您确实为按钮指定 actionCommand
属性,并且您仍然想知道文本(这对我来说很奇怪),您可以使用更多类似...
Now, if you do specify the actionCommand
property for the button AND you still want to know the text (which seems weird to me) you could use something more like...
@Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source instanceof JButton) {
JButton btn = (JButton)source;
String butSrcTxt = btn.getText();
}
}
这篇关于使用动作侦听器获取JButton的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文