File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Swing / AWT / SWT and the fly likes getSource method and object comparison Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "getSource method and object comparison" Watch "getSource method and object comparison" New topic
Author

getSource method and object comparison

Andrew Symantec
Greenhorn

Joined: Apr 24, 2003
Posts: 15
hi all, I have a question troubled me for long time.
Too often, in Swing we can see statements like this:
JButton button1 = new JButton();
JButton button2 = new JButton();
.......
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if ( source == button1)
{
........
}
}
The problem is, the type of source is Object, the type of button1 is JButton, how can they do a equality comparison? For two objects, normaly if they have same object type, they can compare for quality.
Can someone help me out?
Thanks
[ August 09, 2003: Message edited by: Andrew Symantec ]
Nathan Pruett
Bartender

Joined: Oct 18, 2000
Posts: 4121

Because == tests the equality of the reference, not the equality of the object data (that is what .equals() is for). The only way == is going to return true on test of two object references is if both are simply different references to the same object.



In this case s1 == s2 returns true, but s1 == s3 returns false. They have equivalent data, but reference different objects. s1.equals( s2 ) and s1.equals( s3 ) both return true, because .equals() tests data equivalence.
[ August 09, 2003: Message edited by: Nathan Pruett ]

-Nate
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
Andrew Symantec
Greenhorn

Joined: Apr 24, 2003
Posts: 15
Thanks Nathan.
[ August 09, 2003: Message edited by: Andrew Symantec ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: getSource method and object comparison
 
Similar Threads
What am I doing wrong here????
Null Pointer Exception in a GUI application (2)
AWT-EventQueue-0" - need Help
Recreating Buttons
New to GUI, need help with actionListener and buttons