Alright, been trying for at least an hour.

I want to be able to add functions to a JPanel

JPanel a = new JPanel();
a.setTransparency(color, strength);
or something like that.

Is this even possible?
I am getting sick of overiding the paint method for every panel I create and now would like to have an external class that could do this instead of having it bloat up my main interface code.


6 Years
Discussion Span
Last Post by Virux

Doable, but a bad idea unless you're trying to create some sort of library of common functions that you use. If that is what you're going for create some static methods in a different class where you can call those methods from your paint method. Pass in your Graphics object or whatever objects you need to pass around.

If you're only doing this to remove bloat, don't do it though. Removing bloat isn't a good reason to introduce overhead and complicate the code more.


Well if it is doable, how do I do it? Haha

Could you breifly go over it or send me to an article?
I'm mainly looking to expand my knowledge, not so much worried about the code either. I'll be the only one using this application.

Adding an image could easily be acheived with

protected void paintComponent(Graphics g) {
    Dimension d = getSize();
    imageIcon ii = new ImageIcon("Bwaha.jpg");
    g.drawImage(ii.getImage(), 0, 0, d.width, d.height, null);
    // or simply the following inside a seperate class
    drawImage(g, "Bwaha.jpg");

But I would like to know how I could do
Since that is far more readable without having to add the paintComponent function.

I know-- I'm probably killin' ya here. But it's something I would like to add to my knowledge base.

Haha, thanks.


You don't, since you quite obviously have never heard of inheritance, class hierarchies, etc. etc..
First learn Java well, then start thinking about meddling with things like creating customised GUI libraries.


Like jwenting said, there are many concepts in OOP and Java that are more important to learn than what you're trying to do. If you're insistent, here's how you could at least learn an important concept along the way. If you make a class that extends JPanel (inheritance), you could add your own setImage method. Then when you used your class in the future, you could do things like JPanel.setImage("imagePath.jpg").


Edited by BestJewSinceJC: n/a


Yes, thank you for the link.
Exactly what I was looking for.

Thank you very much both of you.
Wasn't sure what it was called(inheritance) so I couldn't really Google it.

Very awesome.

This question has already been answered. Start a new discussion instead.
Take the time to help us to help you. Please be thoughtful and detailed and be sure to adhere to our posting rules.