I am new in Java and I am currently creating a game with graphics. I have this class that extends from JFrame
. In this class, I have many JPanel
s that needs an image as background. As I know, to be able to paint images in the JPanel, I need to have a separate class that extends from JPanel and that class's paintComponent
method will do the work. But I don't want to make separate classes for each JPanel
, I have too many of them; and with the fact that I am only concerned with the background. How can I do this? is it with an anonymous inner class? How?
For better understanding I provided some code:
public GUI extends JFrame {
private JPanel x;
...
public GUI() {
x = new JPanel();
// put an image background to x
}
Why not make a single class that takes a
Image
??You would even provide hints about where it should be painted.
This way, you could simply create an instance when ever you needed it
Updated
The other question is, why?You could just use a
JLabel
which will paint the icon for you without any additional work...See How to use labels for more details...
This is actually a bad idea, as
JLabel
does NOT use it's child components when calculating it's preferred size, it only uses the size of the image and the text properties when determining it's preferred size, this can result in the component been sized incorrectlyYou don't have to make another class for it? You could just do:
You can do this in single line:
panelInstance.add(new JLabel(new ImageIcon(ImageIO.read(new File("Image URL")))));
I hope it will work for you.