The example in this article mainly implements the function of dragging the mouse to draw lines in Java. In order to achieve the function of drawing lines, implements MouseListener and MouseMotionListener are used respectively, and the start and end coordinates of mouse drag are obtained by mousePressed() and mouseReleased(). This is a good example of mastering Java mouse events.
The specific implementation code is as follows:
import java.awt.*;import java.awt.event.*;import javax.swing.*;public class MouseDemo extends JFrame implements MouseListener, MouseMotionListener { int flag; //flag=1 represents Mouse Moved, flag=2 represents Mouse Dragged int x = 0; int y = 0; int startx, starty, endx, endy;//Start coordinates and end coordinates public MouseDemo() { Container contentPane = getContentPane(); contentPane.addMouseListener(this); contentPane.addMouseMotionListener(this); setSize(300, 300); show(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } /*Get the start and end coordinates of mouse dragging from mousePressed(), mouseReleased()*/ public void mousePressed(MouseEvent e) { startx = e.getX(); starty = e.getY(); } public void mouseReleased(MouseEvent e) { endx = e.getX(); endy = e.getY(); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } /*mouseMoved(),mouseDragged() obtain each coordinate of the mouse movement and call the repaint() method*/ public void mouseMoved(MouseEvent e ) { flag = 1; x = e.getX(); y = e.getY(); repaint(); } public void mouseDragged(MouseEvent e) { flag = 2; x = e.getX(); y = e.getY(); repaint(); } public void update(Graphics g) { g.setColor(this.getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); //Clear the current window content paint(g); } public void paint(Graphics g) { g.setColor(Color.black); if (flag == 1) { g.drawString("Mouse coordinates: (" + x + "," + y + ")", 10, 50); g.drawLine(startx , starty, endx, endy); } if (flag == 2) { g.drawString("Drag mouse price coordinate: (" + x + "," + y + ")", 10, 50); g.drawLine(startx, starty, x, y); } } public static void main(String[] args) { new MouseDemo(); }}
During the line drawing process, the program will display the mouse coordinates when dragging. Readers can also modify and improve the program according to their own needs to make it more practical.