JLabel Click Event

If you have two JLabelin JFramewith the same click event MouseListeneradded to them, how can you determine which one JLabelwas clicked without creating a second actionlistener?

Note: both labels have the same text written on them, so they cannot be used to separate them.

+3
source share
4 answers

Just create two fields JLabeland then check the source MouseEvent:

if (e.getSource() == firstLabel) {
  ...
} else if (e.getSource() == secondLabel) {
  ...
}
+4
source

This will give you a link to the component ...

public void mousePressed(MouseEvent e) 
{
JComponent reference = e.getComponent();
}

See Swing Tutorial on MouseListeners for a more complete description .

+5
source

, , . , , , . myButton.getText(); ( JTextfield). :

JTextField textfield = new JTextField("", 37);  
JButton myButton = new new JButton("button text here");  
myButton.addActionListener(new MyActionListener (textfield, myButton));

:

//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);  
    }  
 }

the same principle applies when accessing a button. you can send by line, and this line can be used in conditional statements to determine which button was pressed.

0
source

Since you are using JLabel, which comes from JComponent, it has a method called putClientProperty ("myValue", myValue). You can add a unique identifier there after creating the JLabel and get it during the event using getClientProperty ("myValue"), and then check it.

0
source

Source: https://habr.com/ru/post/1789901/


All Articles