I'm trying to write a program that will show a line between the first click and mouse position after the 1st click. Then after the 2nd click, it shows a line.
I know I will have to use MouseListener
getX()
, getY()
to get the position where the mouse click is at, but the part where I am confused is to show a line between the first click and mouse position then after the second click it shows a line. The tutorial I found online only show me how to draw a line between two mouse clicks.
Would greatly appreciate if anyone can point me in the right direction.
CodePudding user response:
You need to know three points.
- First click point
- Second click point
- The current mouse point
If both first and second click points are null
, then basically do nothing
If the first click point and current mouse point are not null
and the second point is null
, draw a line between the first and transient point
If both the first and second click points are not null
, then draw a line between those two instead
To make this work, you'll need a MouseListener
and a MouseMotionListener
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Point startPoint;
private Point endPoint;
private Point transientPoint;
public TestPane() {
MouseAdapter ma = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (startPoint == null) {
startPoint = e.getPoint();
} else if (endPoint == null) {
endPoint = e.getPoint();
} else {
endPoint = null;
startPoint = e.getPoint();
}
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
if (startPoint != null && endPoint == null) {
transientPoint = e.getPoint();
repaint();
} else {
transientPoint = null;
}
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (startPoint != null && endPoint != null) {
g2d.setColor(Color.BLUE);
g2d.draw(new Line2D.Double(startPoint, endPoint));
} else if (startPoint != null && transientPoint != null) {
g2d.setColor(Color.RED);
g2d.draw(new Line2D.Double(startPoint, transientPoint));
}
g2d.dispose();
}
}
}