Java JPanel handle mouse event and mouse motion event

Description

Java JPanel handle mouse event and mouse motion event


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JFrame {
  private final JPanel mousePanel; 
  private final JLabel statusBar; 

  public Main() {
    super("Demonstrating Mouse Events");

    mousePanel = new JPanel();
    mousePanel.setBackground(Color.WHITE);
    add(mousePanel, BorderLayout.CENTER); 

    statusBar = new JLabel("Mouse outside JPanel");
    add(statusBar, BorderLayout.SOUTH); 

    // create and register listener for mouse and mouse motion events
    MouseHandler handler = new MouseHandler();
    mousePanel.addMouseListener(handler);
    mousePanel.addMouseMotionListener(handler);
  }/*  ww w .j a v a 2s.c o m*/

  private class MouseHandler implements MouseListener, MouseMotionListener {
    // MouseListener event handlers
    // handle event when mouse released immediately after press
    @Override
    public void mouseClicked(MouseEvent event) {
      statusBar.setText(String.format("Clicked at [%d, %d]", event.getX(), event.getY()));
    }

    // handle event when mouse pressed
    @Override
    public void mousePressed(MouseEvent event) {
      statusBar.setText(String.format("Pressed at [%d, %d]", event.getX(), event.getY()));
    }

    // handle event when mouse released
    @Override
    public void mouseReleased(MouseEvent event) {
      statusBar.setText(String.format("Released at [%d, %d]", event.getX(), event.getY()));
    }

    // handle event when mouse enters area
    @Override
    public void mouseEntered(MouseEvent event) {
      statusBar.setText(String.format("Mouse entered at [%d, %d]", event.getX(), event.getY()));
      mousePanel.setBackground(Color.GREEN);
    }

    // handle event when mouse exits area
    @Override
    public void mouseExited(MouseEvent event) {
      statusBar.setText("Mouse outside JPanel");
      mousePanel.setBackground(Color.WHITE);
    }

    // MouseMotionListener event handlers
    // handle event when user drags mouse with button pressed
    @Override
    public void mouseDragged(MouseEvent event) {
      statusBar.setText(String.format("Dragged at [%d, %d]", event.getX(), event.getY()));
    }

    // handle event when user moves mouse
    @Override
    public void mouseMoved(MouseEvent event) {
      statusBar.setText(String.format("Moved at [%d, %d]", event.getX(), event.getY()));
    }
  }

  public static void main(String[] args) {
    Main Main = new Main();
    Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Main.setSize(300, 100);
    Main.setVisible(true);
  }
}



PreviousNext

Related