I am trying to write a code that when the user clicks once, a little dot shows up, twice a line forms from the first and second clicks, and third forms a triangle out of all the clicks, and clicking again restarts with a dot. Currently I can get my JFrame and JPanel to open, but clicking does nothing. I added in a System.out.print command just to see if my mousePressed method ever ran, but it never does. Here is my code currently:
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TriangleClicker extends JFrame {
private final int width = 700;
private final int height = 800;
private JPanel panel;
private MouseListener listener;
private int p1x;
private int p1y;
private int p2x;
private int p2y;
private int p3x;
private int p3y;
private int count = 0;
private Graphics g;
public TriangleClicker() {
this.setSize(width, height);
this.add(createPanel());
listener = new MousePressListener();
}
public JPanel createPanel() {
panel = new JPanel();
panel.setSize(width, height);
return panel;
}
class MousePressListener extends JComponent implements MouseListener {
public void drawLine1(Graphics g) {
g.drawLine(p1x, p1y, p1x, p1y);
}
public void drawLine2(Graphics g) {
g.drawLine(p1x, p1y, p2x, p2y);
}
public void drawLine3(Graphics g) {
g.drawLine(p3x, p3y, p1x, p1y);
g.drawLine(p3x, p3y, p2x, p2y);
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
if (count == 0) {
p1x = e.getX();
p1y = e.getY();
drawLine1(g);
count++;
System.out.println("1");
}
else if (count == 1) {
p2x = e.getX();
p2y = e.getY();
drawLine2(g);
count++;
}
else if(count == 2) {
p3x = e.getX();
p3y = e.getY();
drawLine3(g);
count++;
}
else if(count == 4) {
g.clearRect(0, 0, WIDTH, HEIGHT);
p1x = e.getX();
p1y = e.getY();
p2x = 0;
p2y = 0;
p3x = 0;
p3y = 0;
drawLine1(g);
count = 1;
}
}
@Override
public void mouseReleased(MouseEvent e) {
}
}
}
Any help would be greatly appreciated. Thanks.