Wololo
Wololo

Reputation: 861

Custom painting not working as intended

I'm making a GUI application which finds and draws convex hull for a set of points.

Here's the frame:

public class Frame extends JFrame{
Panel panel = new Panel();
JButton drawHull = new JButton("Draw Convex Hull");
Frame(String title) {
    super(title);
    // setLayout
    setLayout(new BorderLayout());
    // add components to the frame
    add(panel, BorderLayout.CENTER);
    add(drawHull, BorderLayout.SOUTH);
    // add actionListener for drawHull button
    drawHull.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            panel.drawConvexHull();
        }
    }
    );
}
}

The frame contains a button (at the bottom of the frame) and a Panel object.

Here's the Panel class:

public class Panel extends JPanel{
ArrayList<Point> points = new ArrayList<Point>();
public Panel() {
    addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            points.add(new Point(e.getX(), e.getY()));
            repaint();
        }
    });
}
@Override
protected void paintComponent(Graphics g) {
    if(!points.isEmpty()) {
        Point p = points.get(points.size()-1);
        g.fillOval(p.x-2, p.y-2, 4, 4);
    }
}
public void drawConvexHull() {
    // code for finding convex hull
}
}

I have added a mouseListener to the Panel class so that when the user clicks anywhere on the panel, a point is drawn.

When I run the code, everything looks fine. Here's a sample run.

enter image description here

Now here's the problem:

As soon as I click the panel, this happens

enter image description here

A button appears on the top of the frame. Why is this happening?

One more thing. When I click this button on the top, a point is drawn. Here, have a look:

enter image description here

Upvotes: 0

Views: 52

Answers (1)

Reimeus
Reimeus

Reputation: 159754

Without calling super.paintComponent(g) in paintComponent the background is not repainted leading to unpredictable results on the panel component.

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    for (Point point: points) {
        g.fillOval(point.x - 2, point.y - 2, 4, 4);
    }
}

Upvotes: 3

Related Questions