简体   繁体   中英

Java GUI create three JPanel in one JFrame

I have a problem with Java GUI.

I want to create three JPanel instances which have size different in one JFrame . JFrame size 300x800 and Panel1 300x200, Panel2 300x100 and Panel3 300x500. I want to add this panels under by under.

How to solve this problem?

Use a BorderLayout 1 .

  • Add panel1 to the NORTH
  • Add panel2 to the CENTER
  • Add panel3 to the SOUTH

EG

有色面板

Stretch your imagination that the heights are ten times bigger.

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

class ColoredPanels {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JPanel gui = new JPanel(new BorderLayout(3,3));
                gui.setBackground(Color.BLUE);
                gui.setBorder(new EmptyBorder(5,5,5,5));

                JPanel panel1 = new JPanel();
                panel1.setPreferredSize(new Dimension(300,20));
                panel1.setBackground(Color.RED);
                gui.add(panel1, BorderLayout.NORTH);

                JPanel panel2 = new JPanel();
                panel2.setPreferredSize(new Dimension(300,10));
                panel2.setBackground(Color.ORANGE);
                gui.add(panel2, BorderLayout.CENTER);

                JPanel panel3 = new JPanel();
                panel3.setPreferredSize(new Dimension(300,50));
                panel3.setBackground(Color.YELLOW);
                gui.add(panel3, BorderLayout.SOUTH);

                // a frame would need pack() etc.
                JOptionPane.showMessageDialog(null, gui);
            }
        });
    }
}

BTW

  1. Use BorderLayout , .. or BoxLayout as mentioned by Shakedown.
  2. The panels as described will not fit into the frame at that size. A frame has its own decorations to account for (title bar, menus, borders etc.)
  3. Please use camelCase for attribute names.

You can try sizing your panels with setPreferredSize() and company. Then look into using a BoxLayout on your frame, which will put your panels in a row or column.

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