If you have two JLabel
s in a JFrame
both with the same MouseListener
click event added to them, how开发者_如何学运维 can you tell which JLabel
was clicked without creating a second actionlistener?
Note: both labels have the same text written on them so that cannot be used to tell them apart.
This will get you a reference to the component ...
public void mousePressed(MouseEvent e)
{
JComponent reference = e.getComponent();
}
For a more complete description look at the Swing Tutorial on MouseListeners
Just make the two JLabel
s fields and then check the source of the MouseEvent
:
if (e.getSource() == firstLabel) {
...
} else if (e.getSource() == secondLabel) {
...
}
take for example, a keyboard. what I did when I created one, is sent over the button to the action listener. I then had the action listener do a myButton.getText(); and I would just type the text onto my screen (a JTextfield in my case). in your main method write:
JTextField textfield = new JTextField("", 37);
JButton myButton = new new JButton("button text here");
myButton.addActionListener(new MyActionListener (textfield, myButton));
the full action listener would look like this:
//thisMethod is for a keyboard typing into a JTextfield
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.lang.*;
class MyActionListener implements ActionListener {
JTextField textfield;
MyActionListener(JTextField textfield, JButton button) {
this.textfield = textfield;
}
public void actionPerformed(ActionEvent e) {
String letter = javax.xml.bind.DatatypeConverter.printString(textfield.getText()).concat(button.getText());
textfield.setText (letter);
}
}
this same priciple applies when refering to which button was pressed. you could send over a string, and that string could be used in conditional statements to determine which button was pressed.
Since you are using JLabel which comes from JComponent it has a method called putClientProperty("myValue", myValue). You could put some unique identifier in there upon JLabel creation and retrieve it at event time with getClientProperty("myValue") and then test it.
精彩评论