Drawing graphics on top of JButton

I have a situation where I have a bunch of JButtons on a GridLayout. I need each of the JButtons to have:

  • background image (but keep the ability to hold the default button if necessary)
  • custom graphics drawn on top by other classes

I have no problems with the background image since I am using setIcon (), but I am having problems drawing over the background. At some point, I was able to draw on top of the button, but after clicking the button, the pictures disappeared. How to force the button to save this drawing state?

Basically, I need my JButtons to have public methods that let another class draw something on it, for example:

public void drawSomething() {
  Graphics g = this.getGraphics();
  g.drawOval(3,2,2,2);
  repaint();
}

or

public Graphics getGraphics() {
  return this.getGraphics();
}

then another class could do this:

button.getGraphics().drawSomething();

The latter is what I am looking for, but the former is equally useful.

? , paintComponent() , , .

+3
2

JButton paintComponent(). , , "" . .

public class MyButton extends JButton {
    private Painter painter;

    public void paintComponent(Graphics g) {
       super.paintComponent(g);
       painter.paint(g);
    }
}

public interface Painter {
    public void paint(Graphics g);
}

, , , .

+8

BufferedImage , paintComponent (...).

DrawOnImage .

+3

Source: https://habr.com/ru/post/1736061/


All Articles