0

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.

Arrvi
  • 539
  • 6
  • 13
  • 1
    `"I'm not calling super.paintComponent(g) because I don't want default look to be painted."` -- and this is likely why you're experiencing the problems that you're seeing. Have you considered using Icons instead of overriding paintComponent? You can draw your oval in a BufferedImage over a transparent background and use this as your Icon. You may need to create separate Icons for pressed and hover state. – Hovercraft Full Of Eels Nov 14 '14 at 21:48
  • I applied your solution and it works great. Do you think that creating images within `setBounds` method is good idea? – Arrvi Nov 14 '14 at 22:17
  • I think that usually using `setBounds(...)` is a bad idea. I would make sure to create the images only once and not many times. – Hovercraft Full Of Eels Nov 14 '14 at 22:21
  • In this case it does not really matter, but let's assume that buttons change their size - `setBounds` is the first (is it?) method that 'knows' that fact, and it is called once as opposed to painting methods. – Arrvi Nov 14 '14 at 22:49
  • If you're using Icons, I believe that the JButton's own `getPreferredSize()` method (the most important method relevant to your problem) would know the size of the icons and size accordingly. – Hovercraft Full Of Eels Nov 15 '14 at 00:18

0 Answers0