I am trying to listen to mouse events coming from both a JLabel and a JTextField. However, I am only able to listen to mouse events from JLabel, but not JTextField.
Consider this code:
class FieldPanel extends JPanel{
JLabel label;
JTextField text;
public FieldPanel(){
label = new JLabel("This is a test label");
text = new JTextField("This is a test field");
add(label);
add(text);
}
}
class OuterPanel extends JPanel{
FieldPanel fieldPanel;
public OuterPanel(){
fieldPanel = new FieldPanel();
fieldPanel.addMouseListener(new MouseAdapter(){
@Override
public void mousePressed(MouseEvent event) {
System.out.println("Mouse pressed !!");
}
});
add(fieldPanel);
}
}
public class UITest{
public static void main (String args[]){
JFrame frame = new JFrame();
OuterPanel outerPanel = new OuterPanel();
frame.getContentPane().add(outerPanel);
frame.pack();
frame.setVisible(true);
}
}
The 'Mouse Pressed !!' message is displayed when I click on the JLabel. However, it does not get displayed when I click on the JTextField. Why is this the case?
Thanks!
Thanks for all the answers.
I found some sort of workaround. I am changing my code so that I listen directly to the JTextField
component, as opposed to listening to the panel.