The short answer to your problem is that you need to create a custom component and override the paintComponont
method of that JPanel etc, and then we can perform our custom painting in that method.
For example, we can make a class that extends JPanel
that also includes the mouse click event:
public class MyCustomPanel extends JPanel implements MouseListener
{
//If you want to dynamically draw dots then use a list to manage them
ArrayList<Point> points = new ArrayList<>();
//Here is where the painting happens, we need to override the default paint behaviour, then add our own painting
@Override
protected void paintComponent(Graphics g)
{
//Call this first to perform default painting (borders etc)
super.paintComponent(g);
//Here we can add our custem painting
Graphics2D draw = (Graphics2D) g;
draw.drawString("Example painting", 10, 10);
//If you want to dynamically draw dots then use a list to manage them:
for (Point point : points)
{
draw.drawLine(point.x, point.y, point.x, point.y);
}
}
//Add a new point and refresh the graphics
@Override
public void mouseClicked(MouseEvent e)
{
points.add(new Point(e.getX(), e.getY()));
this.repaint();
}
}
Then to insert the myCustomPanel
we don't use the UI generator, instead we can add it directly to the JFrame like this:
MyCustomPanel panel = new MyCustomPanel();
yourJFframe.add(new myCustomPanel());