Skip to main content
gamedev.net
🔒 Locked

[java] help with all the LISTENERS : /

Started by jake_Ghost 8 replies 1.6k views
Original Post
jake_Ghost
jake_Ghost
i have started using all the listeners but they are a big pain. When i add lets say, the mouse listener, i cant tell which object fired it. Which is a really big pain when drawing button pictures, ect. Could anyone tell me how to figure out which object fired a mouse over or w/e? thx jake
Kippesoep
Kippesoep
The event object that is passed into your event handler has a method called getSource, which returns an Object that triggered the event.
Kippesoep
H_o_p_s
H_o_p_s
import javax.swing.JButton;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JPanel;class Main extends JPanel implements ActionListener {	JButton btLoad;	JButton btSave;	public Main () {		btLoad = new JButton( "Load"  );		btLoad.addActionListener( this );		btSave = new JButton( "Save"  );		btSave.addActionListener( this );	}	public void actionPerformed( ActionEvent e ) {		if (e.getSource() == btLoad)			System.out.println("Pressed the Load Button");		if (e.getSource() == btSave)			System.out.println("Pressed the Save Button");	}}

This is a Panel that has two buttons, Load and Save...
Hope this helps!
BRING BACK THE BLACK (or at least something darker)
jake_Ghost
jake_Ghost
thx that helps alot for buttons and such but how would i use that with the MouseListener?
CaptainJester
CaptainJester
Quote:
Original post by jake_Ghost
thx that helps alot for buttons and such but how would i use that with the MouseListener?


It is done the same way. If you look at the API for events, all event objects derive from java.awt.Event. They all will inherit getSource() from this. Any object that throws an event can be found out with getSource().
"None of us learn in a vacuum; we all stand on the shoulders of giants such as Wirth and Knuth and thousands of others. Lend your shoulders to building the future!" - Michael Abrash[JavaGaming.org][The Java Tutorial][Slick][LWJGL][
phil05
phil05
I had the same question about this subject.

if (e.getSource() == btnLoad)


How can this code consider my input? What if the button needed a double click instead of a single click? What if I hovered over it? With a C# background, it was much more clear on what its doing. This code above does not. Why is that, and how can it be used for such?
phil05
phil05
Okay, thanks. I'm glad there are solutions.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.