0

I need to extend a JPanel so that upon a certain condition, it paints a semi-transparent overlay over the whole avaiable space.

From other answers I gathered that in this case, one should override paint() instead of paintComponent(), so that I can draw after the components have been painted, but I had no luck overriding either.

Overriding paintComponent() will draw behind the components on the JPanel. Overriding paint() draws in front of them, but moving the mouse over the JButtons repaints them, and they come on top.

For example this will work, but the JButtons come on top if hovered:

@Override
    public void paint(Graphics g){
        super.paint(g);  //also tried without this call
        Graphics2D g2d = (Graphics2D)g;
            g2d.setColor(BK_COLOR);
        g2d.fillRect(0,0,getWidth(), getHeight());      
    }

What am I doing wrong?

Lory A
  • 520
  • 1
  • 5
  • 17
  • 1
    *"From other answers I gathered that in this case, one should override paint() instead of paintComponent()"* - That's actually, not true, Swing components can be painted independently of their parent, meaning, your `paint` method may not be called when a child component repaints – MadProgrammer Jan 27 '17 at 02:11
  • I see. So how do I get around that? Because it seems like that's exactly the case. Surely I don't have to repaint it every time with a mouseListener on every JButton..? – Lory A Jan 27 '17 at 02:15
  • 1
    Generally `JLayer`/`JXLayer` is a better solution, for [example](http://stackoverflow.com/questions/29143251/how-to-make-a-blurry-jframe-jdialog-in-java-using-swing-and-jlayer/29143478#29143478), [example](http://stackoverflow.com/questions/14286484/putting-marks-on-imageicon-in-jlabel/14287485#14287485) and [example](http://stackoverflow.com/questions/12982863/secure-desktop-mode-effect-for-java-application/12983564#12983564) – MadProgrammer Jan 27 '17 at 02:15
  • 1
    Once upon a time, you would have had to resort to using the frame's `glassPane`, but now we `JLayer`, which is a kind of "glass pane for components", for my previous comment for some examples – MadProgrammer Jan 27 '17 at 02:16
  • @MadProgrammer Thanks it works just fine. Post this as an answer please, so I can select it and people can read, for generations to come ! – Lory A Jan 27 '17 at 02:29
  • [This one's](http://stackoverflow.com/questions/27516581/how-to-highlight-uniform-visually-select-draw-transparent-overlay-jpanel/27516784#27516784) probably closer to what your asking ;) – MadProgrammer Jan 27 '17 at 02:35

0 Answers0