Search for buttons in jpanel and get the button's text?

Hi I have a problem about getting the text from the buttons in a JPanel. My program will have a JPanel and there are 4 buttons inside it. Each button will have a random integer shown as a text. I want my program to be able to get the key that is pressed from the keyboard, and check if that key is matched with any of the buttons' text (Something like the calculator). If the key is matched with any buttons in the JPanel, it will print out that key and make that button disabled.

My code is something like:

private void formKeyPressed(java.awt.event.KeyEvent evt) {                                
    Component[] comp = numpanel.getComponents();
    for (int i = 0;i<comp.length;i++) {
        if (comp[i] instanceof JButton) {

             //check if it matches with any button's text

        }
    }
}                               

and I get an error when I try to write comp[i].getText() in order to check the key and the button's text. In my understanding, it says that comp[i] is a Component, which doesn't have the method getText(), am I understand it correctly ?

How can i fix it or are they any alternative ways to do this?

Upvotes: 1

Views: 4735

Answers (1)

NESPowerGlove
NESPowerGlove

Reputation: 5496

it says that comp[i] is a Component, which doesn't have the method getText(), am I understand it correctly ?

Yes.

How can i fix it or are they any alternative ways to do this?

If you know that comp[i] is a JButton, such as within the if statement you have where you checked that it is with instanceof, then you can cast it as a JButton, and use the getText() method.

.... = ((JButton)comp[i]).getText();

Upvotes: 4

Related Questions