java MouseListener接口

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java MouseListener接口相关的知识,希望对你有一定的参考价值。

import javax.swing.*;

class First{
    public static void main(String args[]){

        Second gui = new Second();
        gui.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        gui.setSize(300, 200);
        gui.setVisible(true);

    }
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Second extends JFrame {

   private JPanel mousePanel;
   private JLabel statusBar;

   public Second(){
       super("title");

       mousePanel = new JPanel();
       mousePanel.setBackground(Color.RED);
       // Settomg the layout to be centered
       add(mousePanel, BorderLayout.CENTER);

       // Setting the statusBar default text to "Default" & setting the layout to NORTH (up)
       statusBar = new JLabel("Default");
       add(statusBar, BorderLayout.NORTH);

       // Creating an object to pass in the event listener
       HandlerClass handler = new HandlerClass();
       // Assigning an event listener to the mousePanel and passing in the handler object
       mousePanel.addMouseListener(handler);
       mousePanel.addMouseMotionListener(handler);

   }

   // Creating the HandlerClass and implementing MouseListener & MouseMotionListener for all to be overriden
   private class HandlerClass implements MouseListener, MouseMotionListener{

       // Overriding the methods from the libraries and setting the designated event for each one
        public void mouseClicked(MouseEvent event){
            statusBar.setText(String.format("Clicked at X:%d Y:%d", event.getX(), event.getY()));
        }
        public void mousePressed(MouseEvent event){
            statusBar.setText("Mouse Pressed");
        }
        public void mouseReleased(MouseEvent event){
            statusBar.setText("Mouse Released");
        }
        public void mouseEntered(MouseEvent event){
            statusBar.setText("Mouse Entered MousePanel");
        }
        public void mouseExited(MouseEvent event){
            statusBar.setText("Mouse Exited MousePanel");
        }
        // Mouse Motion Events:

       public void mouseDragged(MouseEvent event){
            statusBar.setText("Mouse Dragged");
       }
       public void mouseMoved(MouseEvent event){
           statusBar.setText("Mouse Moved");
       }

   }
}

以上是关于java MouseListener接口的主要内容,如果未能解决你的问题,请参考以下文章

Java中是不是存在用于满足接口的空方法的习语?

MouseListener

Java 鼠标事件监听MouseListener

Java Swing界面编程(25)---事件处理:鼠标事件及监听处理

java图形界面 运行时如何在点击鼠标时 改变字体颜色或者大小

除非与mouselistener一起使用,否则JLabel不会显示