user3763329
user3763329

Reputation: 3

Having multiple JPanel's in JFrame with background?

I have the following code:

public void init() {
    setLayout(new BorderLayout(0, 0));
    setIconImage(ResourceUtility.getImage("logo.png").getImage());
    final JPanel container = new JPanel() {
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(logo, getWidth() / 2 - logo.getWidth(null) / 2, getHeight() - (int) (getHeight() * 0.90), null);
        }
    };
    container.setBackground(UIConfiguration.ColorRedDark);
    add(container);

    pack();
    setLocationRelativeTo(null);
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setExtendedState(MAXIMIZED_BOTH);
    setMaximumSize(UIConfiguration.screenSize);
    setVisible(true);
}

Now, when I try to add another JPanel under it, it loses the background plus the image. How can I prevent this?

Upvotes: 0

Views: 583

Answers (2)

Paul Samsotha
Paul Samsotha

Reputation: 208984

What looks to be your problem is that container is locally scoped in the init method. So you can't access it (not without some component searching of the frame) to add other components to (which is what you want to do).

You are probably trying to add other components to the frame, thinking that this will add them to container. Once you add another component to the frame by just doing add(secondPanel). What this basically does (with the frame BorderLayout) is add(secondPanel, BorderLayout.CENTER), implicitly. But you have already done add(container), which is the same as add(container, BorderLayout.CENTER), and each position can only have one component. So the conatiner is kicked out, leaving only the secondPanel

So a simple fix would just be to take the container declaration out of the init method, and add components to the container

Also keep in mind that JPanels are opaque by default, so adding a JPanel to container will cause the JPanels background to cover up the container background. So if you want to and a JPanel to the container, make sure to setOpaque(false) on the JPanel.

Upvotes: 1

user4165285
user4165285

Reputation: 11

Use panel.setOpaque(false) for set no background on child JPanel objects.

Upvotes: 1

Related Questions