Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing overriding object's paintComponent

If I have a JPanel object that I can't modify, is there a way I can modify the paintComponent method of it without using injection?

One approach I was thinking of was getting the JPanel's Graphics object, passing it to paintComponent(), performing operations on this Graphics object, and finally painting that in my custom JPanel. The problem with this, is I need to be able to do this every time the original JPanel's paintComponent() is called.

I don't need to replace what's in paintComponent(), I just need to add on to it.

For example:

JFrame frame = null;
for (Frame f : JFrame.getFrames()) {
  if (((JFrame) f).getTitle().equals("Title")) {
    JPanel panel = null;
    // ... Cycle through all components and get the one that's a JPanel

    // I want to use ColorConvertOp to make panel greyscale
  }
}
like image 312
LanguagesNamedAfterCofee Avatar asked Dec 07 '22 13:12

LanguagesNamedAfterCofee


2 Answers

One approach would be to use the Decorator Pattern to wrap the existing class. Your decorator can then implement paintComponent to first delegate to the original component and after that paint on top of it. For this approach you need to actually gain control over the creation of the components, or you need to replace them after the component hierarchy has been created (using getComponents() of the parent container to find the components to be altered).

like image 178
Durandal Avatar answered Dec 09 '22 03:12

Durandal


I think one possibility is to use a GlassPane and position it exactly over your JPanel (maybe let it follow the panel using listeners if the panel changes its location). Then you can simply draw your stuff in the glasspane and it will be overlayed.

Of course this is not really elegant... But I don't see any possibility to change the paintComponents behaviour of an already existing instance without injection. (Proof me wrong, Java geeks of this world! :P)

like image 44
brimborium Avatar answered Dec 09 '22 01:12

brimborium