Custom painted JButton shows artifacts on hover

156 views Asked by At

I'm writing little game that requires small buttons over custom painted JPanel. My solution is quite simple, but it has some issues.

class TargetButton extends JButton {
    private Point point;

    public TargetButton(Point point) {
        this.point = point;
    }

    public Point getPoint() {
        return point;
    }

    @Override
    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        g2.setPaint(Color.RED.darker());
        g2.draw(new Ellipse2D.Double(0, 0, getWidth()-1, getHeight()-1));
    }
}

They are created like this:

public void setTargets(List<Point> pts) {
    for (Point point : pts) {
        TargetButton target = new TargetButton(point);
        targets.add(target); // list of target buttons
        target.setBounds((int)__(point.getX()), (int)__(point.getY()), (int)(track.getWidth()*scale/resolution), (int)(track.getWidth()*scale/resolution));
        target.addActionListener(this);
        add(target);
    }
    invalidate();
    repaint();
}

Buttons are displayed correctly as circles, but when I hover them, they are painted over black or white background, which looks quite ugly.

I'm not calling super.paintComponent(g) because I don't want default look to be painted. I also tried to extend AbstractButton, but it doesn't respond to clicks.

0

There are 0 answers