Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

In my code, I’ve JLabels which I want to trap with mouse click events. Below is the code implementation for it: 

public void mouseClicked(MouseEvent arg0) {

}

public void mouseExited(MouseEvent arg0) {

}

public void mouseEntered(MouseEvent arg0) {

}

public void mousePressed(MouseEvent arg0) {

}

public void mouseReleased(MouseEvent arg0) {

    System.out.println("Welcome to Java Programming!"); 

}

Can anyone tell me if there’s an efficient way to do this?

1 Answer

0 votes
by (19.7k points)

You can try to use MouseAdapter() like below: 

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class MainClass extends JPanel {

  public MainClass() {

      addMouseListener(new MouseAdapter() { 

          public void mousePressed(MouseEvent me) { 

            System.out.println(me); 

          } 

        }); 

  }

  public static void main(String[] args) {

    JFrame frame = new JFrame();

    frame.getContentPane().add(new MainClass());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setSize(200, 200);

    frame.setVisible(true);

  }

}

Interested in Java? Check out this Java tutorial by Intellipaat. 

No related questions found

Browse Categories

...