0 votes
1 view
in Java by (9.2k 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 (19k 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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...