import java.awt.event.*; import javax.swing.*; public class MouseClickExample extends JButton { public MouseClickExample() { setText("Click Me!"); addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { JOptionPane.showMessageDialog(null, "Button was clicked!"); } }); } public static void main(String[] args) { JFrame frame = new JFrame("Mouse Click Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.add(new MouseClickExample()); frame.setVisible(true); } }
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MousePositionExample extends JPanel { public MousePositionExample() { setPreferredSize(new Dimension(300, 200)); addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { int x = e.getX(); int y = e.getY(); JOptionPane.showMessageDialog(null, "You clicked at: (" + x + ", " + y + ")"); } }); } public static void main(String[] args) { JFrame frame = new JFrame("Mouse Position Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.add(new MousePositionExample()); frame.setVisible(true); } }In this example, we create a custom JPanel component that listens for mouse clicks using the addMouseListener() method. Whenever the mouse is clicked, the MouseEvent object passed to the mouseClicked() method contains the x and y coordinates of the mouse click, which we use to display a message dialog showing the position of the click. Both of these examples use the MouseEvent class to handle mouse events in Java. This class is part of the java.awt.event package library, which contains other event classes for listening to user input.