How to get the type of component clicked?

Asked

Viewed 119 times

2

The getSource() method returns the event source, there is some method that returns the event source type, whether it was a jlabel, or jbutton, something like?

  • http://answall.com/a/46579/4808

2 answers

2

Suppose you have a variable _var which stores the event source, obtained from getSource().

You can get the type of this variable (and any other) with getClass(). The comparison can be made like this:

_var.getClass() == JButton.class

2


you can use the instanceof in an if, checking which class belongs to the object, example:

if(getSource() instanceof JButton){
//Foi clicado em um botão
}
else if(getSource() instanceof JLabel){
//Foi clicado em uma JLabel
}
  • instanceof will return true if the object is an instance of the class or some subclass. If you do not need checking for subclasses prefer getClass() because there is performance gain.

Browser other questions tagged

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