开发者

JLabel click event

开发者 https://www.devze.com 2023-02-08 05:54 出处:网络
If you have two JLabels 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?

If you have two JLabels 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 JLabels 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消