import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MouseListenerExample extends JPanel implements MouseListener { public MouseListenerExample() { addMouseListener(this); } public void mouseClicked(MouseEvent e) { System.out.println("Mouse clicked"); } public void mouseEntered(MouseEvent e) { System.out.println("Mouse entered"); } public void mouseExited(MouseEvent e) { System.out.println("Mouse exited"); } public void mousePressed(MouseEvent e) { System.out.println("Mouse pressed"); } public void mouseReleased(MouseEvent e) { System.out.println("Mouse released"); } public static void main(String[] args) { JFrame frame = new JFrame("MouseListener Example"); frame.setSize(300, 300); MouseListenerExample panel = new MouseListenerExample(); frame.add(panel); frame.setVisible(true); } }
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ColorChangerPanel extends JPanel implements MouseListener { Color color; public ColorChangerPanel() { color = Color.RED; addMouseListener(this); setPreferredSize(new Dimension(100, 100)); } public void mouseClicked(MouseEvent e) { if(color == Color.RED) { color = Color.BLUE; } else { color = Color.RED; } repaint(); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(color); g.fillRect(0, 0, getWidth(), getHeight()); } public static void main(String[] args) { JFrame frame = new JFrame("Color Changer Example"); frame.setSize(300, 300); ColorChangerPanel panel = new ColorChangerPanel(); frame.add(panel); frame.setVisible(true); } }This example creates a JPanel that changes color when clicked. The panel implements the MouseListener interface and sets itself as the mouse listener using addMouseListener(). When the panel is clicked, the color toggles between red and blue and the panel is repainted. Package/library: javax.swing