如何将组件添加到 JPanel

How to add Components into a JPanel

我只想在面板中添加几个组件并设置面板背景color.But我做不到。谁能建议我,怎么做?这是我的代码。

public Multiple2() {
        getContentPane().setLayout(null);

        JPanel p1 = new JPanel();
        p1.setBackground(Color.RED);
        getContentPane().add(p1,BorderLayout.SOUTH);

        lb1 = new JLabel("Enter the First Number: ");
        lb1.setBounds(10, 10, 250, 20);

        tf1 = new JTextField(100);
        tf1.setBounds(155, 10, 400, 20);

        lb2 = new JLabel("Enter the Second Number: ");
        lb2.setBounds(10, 35, 250, 20);

        tf2 = new JTextField(100);
        tf2.setBounds(155, 35, 400, 20);

        getContentPane().add(lb1);
        getContentPane().add(tf1);
        getContentPane().add(lb2);
        getContentPane().add(tf2);


        setVisible(true);
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

您似乎试图将 p 添加到 contentPane 的 BorderLayout.SOUTH 位置,但您删除了 contentPane 的布局管理器,因此它没有南位置,所以你在任何地方都看不到 p1。

要向 p1 JPanel 添加组件,您需要像使用 JFrame 的 contentPane 一样使用 add(...) 方法。所以而不是

getContentPane().add(foo);

你会这样做:

p1. add(foo);

那么您可能需要将 p1 JPanel 添加到 contentPane 的 BorderLayout.CENTER 位置,而不是使用 null 布局。

虽然空布局和 setBounds() 对于 Swing 新手来说似乎是创建复杂 GUI 的最简单和最好的方法,但您创建的 Swing GUI 越多,您在使用时 运行 遇到的困难就越严重他们。它们不会在 GUI 调整大小时调整您的组件的大小,它们是皇家 来增强或维护的,当放置在滚动窗格中时它们完全失败,当在所有平台或不同的屏幕分辨率上查看时它们看起来很糟糕来自原来的

例如:

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;

public class Mult2 extends JPanel {
    private JTextField field1 = new JTextField(10);
    private JTextField field2 = new JTextField(10);

    public Mult2() {
        setLayout(new GridBagLayout());

        add(new JLabel("Enter the First Number:"), createGbc(0, 0));
        add(field1, createGbc(1, 0));
        add(new JLabel("Enter the Second Number:"), createGbc(0, 1));
        add(field2, createGbc(1, 1));

        setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        setBackground(Color.PINK);
    }

    private static GridBagConstraints createGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridheight = 1;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        int right = x % 2 == 0 ? 15 : 5;
        gbc.insets = new Insets(5, 5, 5, right);
        return gbc;
    }

    private static void createAndShowGui() {
        Mult2 mainPanel = new Mult2();

        JFrame frame = new JFrame("Multiply");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}