使用动作侦听器获取JButton的文本 [英] Get the text of a JButton using a Action Listener

查看:73
本文介绍了使用动作侦听器获取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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆