Alright, been trying for at least an hour.

I want to be able to add functions to a JPanel
Example,

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

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.

Thanks

Recommended Answers

All 5 Replies

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);
    super.paintComponent(g);
    // or simply the following inside a seperate class
    drawImage(g, "Bwaha.jpg");
}

But I would like to know how I could do
myJPanel.setImage("bwaha.jpg");
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").

http://java.sun.com/docs/books/tutorial/java/IandI/subclasses.html

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.