Jump to content

getSource() in actionPerformed?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
Dina

Dina

    Newbie

  • Members
  • Pip
  • 2 posts
I'm having a problem where i've got 2 buttons, I've added actionListeners to both with
	build.addActionListener(this);
	prebuilt.addActionListener(this);

and I'm using
public void actionPerformed (ActionEvent event)
{
	System.out.println("click");
	if (event.getSource() == build)
		{
		System.out.println("build clicked");
		}
	if (event.getSource() == prebuilt)
		{
		System.out.println("Prebuilt clicked");
		}
}

to differentiate between the two buttons but neither of them do what they are supposed to.
If I click either then it says "click" like its supposed to but its not telling which is which.

If you get what I mean?

Any help would be greatly appreciated.

Also, if I were to print event.getSource() out to screen should I be getting something as long as this...

javax.swing.JButton[,608,207,110x26,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@1034bb5,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=Build my Bike,defaultCapable=true]

Thanks in advance

#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
What about .equals instead of == ?
I think that, in general, it's often better to choose .equals over ==. In certain cases == is preferred tho.

Like comparing 2 strings
String a = "hey";
String b = "hey";

a==b is probably true.
a.equals(b) is certainly true.

== checks if the reference is the same. The computer stores "hey" somewhere in the memory, and i believe that Java is smart enough to notice that b is equal to a and , to save memory, it creates b with the same reference as a, resulting in equal.

If you explicitly say b = new String("hey"); chances are real that a==b will turn out to be false.

#3
Dina

Dina

    Newbie

  • Members
  • Pip
  • 2 posts
Thanks for the reply.
Turned out I was declaring each button twice.
Thank you though, I will be using .equals more now I understand the difference between it and ==