This article mainly implements the Java drag mouse draw line function, in order to achieve the function of drawing line, respectively with implements MouseListener and Mousemotionlistener, and by mousepressed (), mousereleased () Gets the start and end coordinates of the mouse drag. 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 Mouse
ag=2 represents mouse dragged int x = 0;
int y = 0;
int StartX, Starty, EndX, endy;//starting coordinates with endpoint 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);
}
});
/* by mousepressed (), mousereleased () Gets the start and end coordinates of the mouse drag */public void mousepressed (MouseEvent e) {startx = E.getx ();
Starty = E.gety ();
public void mousereleased (MouseEvent e) {endx = E.getx ();
Endy = E.gety (); The public void mouseentered (MouseEvent e) {} is public void mouseexited (MouseEvent e) {} public void mouseclicked (Mouse Event e) {}/*mousemoved (), mousedragged () gets each coordinate of the mouse movement and calls 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 ());
Clears 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 the mouse price coordinates: (" + x + "," + y + ")", 10, 50);
G.drawline (StartX, Starty, x, y);
} public static void Main (string[] args) {new Mousedemo ();
}
}
The program displays the mouse coordinates as you drag and drop in the line drawing process. Readers can also modify and improve the program according to their own needs, making it more practical.