Java drag and mouse method to draw lines

  • 2020-04-01 03:24:58
  • OfStack

Instance in this paper, mainly realize the function of the Java drag the mouse to draw lines, in order to achieve the function of line drawing, with implements MouseListener and MouseMotionListener, and by mousePressed (), the mouseReleased () to obtain the mouse drag the start and end coordinates. 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 the Mouse version, flag = 2 on behalf of the Mouse Dragged
 int x = 0;
 int y = 0;
 int startx, starty, endx, endy;//Start 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);
  }
 });
 }
 
 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) {
 }
 
 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()); //Clears the current window contents
 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(" Price coordinates of dragging mouse: (" + x + "," + y + ")", 10, 50);
  g.drawLine(startx, starty, x, y);
 }
 }
 public static void main(String[] args) {
 new MouseDemo();
 }
}

The program shows mouse coordinates when dragging and dropping during line drawing. Readers can also modify and improve the program according to their own needs to make it more practical.


Related articles: