简体   繁体   中英

How can I display 2 different panels at the same time?

My first panel's layout is BorderLayout and my second panel's layout is GridBagLayout. I don't know how to show them both at the same time.

I already tried adding two panels to on another panel.

Adding both to another panel is the way to go! But you have to make the right choice of LayoutManager for this "parent" panel. Let me give you an example:

The JFrame 's content pane (where you add all your Component s to) can be setup with a LayoutManager of your choice. See this runnable example, which creates two JPanel s of 100x100 pixels in different colors. The panels are using the LayoutManager s you mentioned, but the main content pane of the JFrame is set to a BoxLayout (horizontal, but you can also set it to vertical!).

You can do this to any other panel, too. A panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); is enough. The below example just uses the content pane, but you can adapt it to your needs:

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

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TwoPanels extends JFrame {

    private static final long serialVersionUID = 1L;
    private static final Dimension DEFAULT_DIMENSION = new Dimension(100, 100);

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

    public TwoPanels() {
        //create panel 1
        JPanel panel1 = new JPanel(new BorderLayout());
        panel1.setPreferredSize(DEFAULT_DIMENSION);
        panel1.setBackground(Color.RED);

        //create panel 2
        JPanel panel2 = new JPanel(new GridBagLayout());
        panel2.setPreferredSize(DEFAULT_DIMENSION);
        panel2.setBackground(Color.GREEN);

        //set content pane layout
        setLayout(new BoxLayout(this.getContentPane(), BoxLayout.X_AXIS));

        //add to content pane
        add(panel1);
        add(panel2);

        //setup and display window
        pack();
        setVisible(true);
    }

}

It looks like this:

在此处输入图片说明

EDIT: It's a little unclear from your question that you actually want to stack overlaying panels . You might find what you need here: https://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM