Get the text of a JButton using a Action Listener

前端 未结 1 1929
醉酒成梦
醉酒成梦 2021-01-25 09:55

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

相关标签:
1条回答
  • 2021-01-25 10:23

    There is a nice and simple trick you can use...

    @Override
    public void actionPerformed(ActionEvent e)
    {
        String butSrcTxt = e.getActionCommand();
    }
    

    If you do not specify the actionCommand for a button, then the text of the button is used instead.

    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();
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题