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
}
}
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).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With