Resize JFrame to JPanels inside JLayeredPane

2019-07-10 05:19发布

问题:

I'm working on a Swing GUI using the JLayeredPane. The JFrame has a JLayeredPane which contains two JPanels. Later I want to display some components in the JPanels, I cut this part of the code to make it shorter for you.

How do I resize the JFrame to the sizes of the JPanels? frame.pack() does not work and without the line setting the preferred size the GUI will show with minimal size.

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

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

public class TestGUI {
    private JFrame frame;
    private JLayeredPane layeredPane;
    private JPanel panelBottom;
    private JPanel panelTop;
    private MainMenuBar menuBar;

    public TestGUI() {
        // panel bottom:
        panelBottom = new JPanel();
        panelBottom.setSize(1000, 500);
        panelBottom.setBackground(new Color(0, 100, 0, 100));
        panelBottom.setLayout(new GridBagLayout());
        // panel top:
        panelTop = new JPanel();
        panelTop.setSize(950, 450);
        panelTop.setBackground(new Color(0, 0, 100, 100));
        panelTop.setLayout(new GridBagLayout());
        // layered pane:
        layeredPane = new JLayeredPane();
        layeredPane.add(panelBottom, 1);
        layeredPane.add(panelTop, 0);
        // frame building:
        frame = new JFrame();
        menuBar = new MainMenuBar();
        frame.setJMenuBar(menuBar);
        frame.setLayout(new BorderLayout());
        frame.setPreferredSize(new Dimension(1100, 600)); // <-- Without this the GUI will be very small
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(layeredPane, BorderLayout.CENTER);
        frame.pack(); // <-- does not work!
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

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

EDIT: I could just change the preferred size line to fit the biggest JPanel, but i ask the question because I want the JFrame to resize depending on the size of the JPanels dynamically.

回答1:

As suggested in How to Use Layered Panes: Laying Out Components in a Layered Pane, "Although a layered pane has no layout manager by default, you can still assign a layout manager to the layered pane." Use OverlayLayout, seen here, for overlapping panels.

Alternatively, use JInternalFrame, which does allow you to pack() the internal frames individually, as shown here and here.