1

I'm trying to use an actionlistener in an array of buttons to change the color of the button then set the string value of the pressed button into the String called Letters. My issue is under my action performed section, the error i'm receiving is "Cannot find Symbol Symbol: getText()

this is the code for adding the actionlistener

for (int i = 0; i < buttons.length; i++) {
        buttons[i] = new JButton(String.valueOf(Alphabet[i]));
        buttons[i].addActionListener(new Pick());
        alphabetWindow.add(buttons[i]);
    }

the code for when the button is pressed.

 static class Pick implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();//gets which button was pressed
        ((Component) source).setBackground(Color.green);
        Letter = ((Component) source).getText();
    }

}

Any help will be greatly appreciated.

Thank you

2
  • Please consider adding stacktrace Commented May 28, 2016 at 2:58
  • 1
    Or use the actionCommand property of the ActionEvent which is defaulted to the text of the button which generated the event Commented May 28, 2016 at 3:02

4 Answers 4

1

Or use the actionCommand property of the ActionEvent which is defaulted to the text of the button which generated the event

public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();//gets which button was pressed
        ((Component) source).setBackground(Color.green);
        Letter = e.getActionCommand();
}
Sign up to request clarification or add additional context in comments.

Comments

0

You should downcast the source to a button. It is impossible for the IDE to infer that you want the method to be called in a deeper class on the class hierarchy.

static class Pick implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();//gets which button was pressed
        ((JButton) source).setBackground(Color.green);
        Letter = ((JButton) source).getText();
    }

}

Comments

0

Component#getText() does not exist and that's the reason why you're receiving the error. Just cast source to a JButton instead.

Letter = ((JButton) source).getText();

Comments

0

Component is a superclass of many controls including buttons and doesn't have the method getText(). You should try something like:

Letter = ((JButton) source).getText();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.