I basically wanna make a single window application where the user will be able to draw segment lines. The application flow should be:
- The user clicks the unique button of the app in order to start the process
- The user selects by clicking the first point of the segment
- The user selects by clicking the second point of the segment
I already have the following piece of code:
public class LineEditor extends JComponent{
private class Point{
int x, y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
private class Line{
Point a, b;
public Line(Point a, Point b){
this.a = a;
this.b = b;
}
}
private ArrayList<Line> lines = new ArrayList<Line>();
public void setLine(Point a, Point b){
lines.add(new Line(a, b));
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Line line : lines) {
g.setColor(line.color);
g.drawLine(line.a.x, line.a.y, line.b.x, line.b.y);
}
}
public static void main(String[] args){
int height = 500, width = 500;
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Properties of the main window
frame.setAlwaysOnTop(true);
final LineEditor lineEditor = new LineEditor();
lineEditor.setPreferredSize(new Dimension(width, height));
JPanel panelCanvas = new JPanel();
panelCanvas.setPreferredSize(new Dimension(width, height));
JPanel secondaryPanel = new JPanel();
JButton addLineButton = new JButton("Add new line");
secondaryPanel.add(addLineButton);
frame.getContentPane().add(lineEditor, BorderLayout.CENTER);
frame.getContentPane().add(panelCanvas, BorderLayout.CENTER);
frame.getContentPane().add(secondaryPanel, BorderLayout.NORTH);
panelCanvas.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
}
});
addLineButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// x
}
});
frame.pack();
frame.setVisible(true);
}
}
I don't get how to:
- Activate the panelCanvas.addMouseListener only after the user has pressed the button.
- Get the mouse coordinates (after the click has been made) from the addLineButton.addActionListener so I can create two Point objects and after that make a call to lineEditor.setLine(pointA, pointB)
I wanna achieve something like:
addLineButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Wait for the first user click
int x1 = mouseListener.getX();
int y1 = mouseListener.getY();
Point a = new Point(x1, y1);
// Wait for the second user click
int x2 = mouseListener.getX();
int y2 = mouseListener.getY();
Point b = new Point(x2, y2);
lineEditor.setLine(a, b);
}
});