mouseinpadaptdemo.java

来自「《java事件处理指南》一书的代码,好东西」· Java 代码 · 共 67 行

JAVA
67
字号
import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;public class MouseInpAdaptDemo extends JFrame {   private JPanel panel;    private int startX, startY, endX, endY;   public MouseInpAdaptDemo()   {/*  A JPanel object is placed on a Frame registers a         *//*  MouseInputListener to receive both motion-oriented and   *//*  non motion-oriented MouseEvents.                         */      panel = new JPanel();      MouseInputHandler listener = new MouseInputHandler();      panel.addMouseListener(listener);      panel.addMouseMotionListener(listener);      getContentPane().add(panel);      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      setBounds(100, 100, 300, 200);      setVisible(true);   }/*  The MouseInputListener is implemented as an inner class that      *//*  extends the MouseInputAdapter class.  When the user presses the   *//*  mouse inside the bounding area of the panel, a MouseEvent is      *//*  generated and sent to the mousePressed() method.  This method     *//*  sets the starting point for the line. When the mouse is dragged   *//*  inside the panel, MouseEvents are generated and sent to the       *//*  mouseDragged() method which draws a line according to the         *//*  position of the mouse.  Because the MouseInputAdapter class is    *//*  used, implementations do not have to be provided for the methods  *//*  declared in the MouseListener and MouseMotionListener interfaces  *//*  that aren't needed for this example.                              */   class MouseInputHandler extends MouseInputAdapter   {      public void mousePressed(MouseEvent event)      {         startX = event.getX();         startY = event.getY();         endX = startX;         endY = startY;      }      public void mouseDragged(MouseEvent event)      {         startX = endX;         startY = endY;         endX = event.getX();         endY = event.getY();         panel.getGraphics().drawLine(startX, startY, endX, endY);      }   }   public static void main(String args[])   {      MouseInpAdaptDemo demo = new MouseInpAdaptDemo();   }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?