Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Requesting help with question being asked.

 
kenny gill
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure how to answer this question and would appreciate some advice:

In the actionPerformed(ActionEvent event) method in the class InputPanel, the first line of code is a decision statement determining if the event.getSource is a JButton. If the source is NOT a JButton, what else would it be?

Why is the decision statement mentioned in the previous question necessary?

Here is the method the question is referring to:

 
Paul Clapham
Sheriff
Posts: 21416
33
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If it's not a JButton, then it would be some other Swing component which supports ActionListeners.

And if that were the case, then casting it to a JButton in line 4 of the posted code would throw a ClassCastException. That would be a bad thing; doing nothing would be better, and that's what line 1 does for you.
 
Darryl Burke
Bartender
Posts: 5148
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where did you get that code, kenny? If it's provided as a sample of bad code that you have to improve, fine. But as an example of Swing and Java coding, it's atrocious.

For making an identity comparison using the == operator, casting is redundant. And since casting isn't needed, neither is the instanceof test.

And apart from all that, it suggests that a class having some other purpose of its own implements ActionListener, which is usually bad style.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic