How to identify the button that was clicked?

Asked

Viewed 1,321 times

0

I have several buttons and I would like to compare the text of the button clicked with a variable of type String.

That without using it:

if (evento.getSource() == botaoXl) {
    // Fazer isto...
} else if (evento.getSource() == botaoY) {
    // Fazer aquilo...
}
  • Why do you want to check for the string? The text of the buttons will be dynamic? You can add a listen to the buttons and perform such behavior. You are using which GUI?

  • 1

    setActionCommand and getActionCommand are there for that.

  • I put the tag swing on your question because that sounds like swing to me. If not, then I ask you to edit the question specifying exactly what the technology or framework you are using.

1 answer

1

How about using ((JButton) evento.getSource()).getText()?

  • I don’t think you even need the.getSource() event. Only the.gettext() button, since the button has already been rendered, returns the text of the button.

  • 1

    @diegofm This supposing that inside the ActionListener there is some reference to the variable of the button that does this. In my design, in a well done project, the button in question within the ActionListener it would be so obvious that this issue would become totally unnecessary and trivial. But looking at the question code, it looks like a super-mega-power-ActionListener generic is used for everything and from there in the code begin to appear these gambis. Unfortunately as we no longer have data on the context of the code, it is difficult to suggest any different approach within the big picture.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.