Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing JLayeredPane not showing up

I seem to be having some major issues with JLayeredPane. I have a BorderLayout() pane, and I'd like for the West-side element to contain a few JLayeredPane's on top of each other, so I can switch between them to show the right information.

The west pane should be 200 pixels wide and should be as long as the total window is. In my sample code I have added two layers to the JLayeredPanel, but they don't show up. They should be in the west pane.

Here is my code:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

public class Main {
    private static JFrame mainFrame = new JFrame();
    private static JPanel mainPane = new JPanel();
    public Main(){}

    public static void initGui(){
        JLayeredPane westPanel = new JLayeredPane();
        westPanel.setPreferredSize(new Dimension(200,0));
        westPanel.setBackground(Color.blue);

        JPanel layerOne = new JPanel();
        layerOne.add(new JLabel("This is layer 1"));
        westPanel.add(layerOne, new Integer(0), 0);

        JPanel layerTwo = new JPanel();
        layerTwo.add(new JLabel("This si layer 2"));
        westPanel.add(layerTwo, new Integer(1), 0);

        JPanel centerPanel = new JPanel();
        centerPanel.setBackground(Color.yellow);

        JPanel eastPanel = new JPanel();
        eastPanel.setPreferredSize(new Dimension(200,0));
        eastPanel.setBackground(Color.red);

        mainPane = new JPanel(new BorderLayout());
        mainPane.add(westPanel, BorderLayout.WEST);
        mainPane.add(centerPanel, BorderLayout.CENTER);
        mainPane.add(eastPanel, BorderLayout.EAST);

        mainFrame = new JFrame("Learning to use JLayeredPane");
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setBounds(200, 200, 800, 500);
        mainFrame.setContentPane(mainPane);
        mainFrame.setVisible(true);
    }

    public static void main(String[] args) {
        initGui();
    }
}

What this results in: enter image description here

like image 310
jdepypere Avatar asked Aug 28 '26 01:08

jdepypere


1 Answers

JLayeredPane uses a null layout and so you are responsible for stating the size and location of all components added to it. If not they will default to a location of [0, 0] and a size of [0, 0].

like image 111
Hovercraft Full Of Eels Avatar answered Aug 30 '26 14:08

Hovercraft Full Of Eels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!