Hathor
Hathor

Reputation: 197

Adding multiple types of Backgrounds to one JFrame

My title is a bit confusing, so I'll try to explain. What I'd like to do is have a background image in my application that stays static in the top center (as in, center on the x axis, and right at the top from the y axis). And I want this even when the JFrame is re-sized. However, underneath that image, I would like a pattern I made to be repeated enough to fit the window size.

I thought of several ways to do this (and used StackOverflow questions that have already been answered) to come up with a logical solution. (I say logical because it doesn't actually work.)

I would use this -

 JPanel panel = new JPanel();
  panel.getContentPane(backgroundImage);
  panel.setSize(400, 400); // JFrame arbitrary size.
  panel.getContentPane().setLayout(null);
  panel.setVisible(true);

  int panelX = (panel.getWidth() - panel.getWidth() - panel.getInsets().left - panel.getInsets().right) / 2;
  panel.setLocation(panelX, 0);

Which is based off of the solution from this - Center a JPanel in a JFrame

The problem I have with this code is that I get an error when I try to use the getContentPane(); (The error is "The method getContentPane() is undefined for the type JPanel".)

And underneath that JPanel, I would have ANOTHER JPanel with the following code -

BufferedImage titledImageFile = ImageIO.read(new File(IMAGE_PATH_TILED));
TiledImage test = new TiledImage(tiledImageFile);

public void paintComponent(Graphics g) {
int width = getWidth();
int height = getHeight();
int imageW = tileImage.getWidth(this);
int imageH = tileImage.getHeight(this);

// Tile the image to fill our area.
for (int x = 0; x < width; x += imageW) {
    for (int y = 0; y < height; y += imageH) {
        g.drawImage(tileImage, x, y, this);
    }
}
}

Hopefully my question is clear; Am I going about this the correct way, or is there something else I should do? Additionally, how do I get the JFrame to work with this?

And finally, if this question is downvoted, please leave an explanation so I can fix/prevent it from happening in the future.

Upvotes: 0

Views: 426

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347334

You to need to built each panel up on top of each other

Start with your JFrame, using a BorderLayout, add you TitledPane to it. This will allow the titled pane to occupy the entire space of the frame.

Set the layout for the TitledPane to GridBagLayout. Using the following constraints, add a JLabel, whose icon property has been set to your image...

GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.anchor = GridBagConstraints.NORTH;

It would, also, be faster if you cached the result of titling to a separate BufferedImage. You would need to update it each time the panel was invalidated, but it would provide a faster repaint...

Upvotes: 1

Related Questions