为什么自定义组件没有显示在 JFrame 上?

Why custom component is not showing up on JFrame?

我创建了一个扩展 JComponent 的自定义组件 InOutList,我想将其添加到那个 JFrame 上。但是它没有出现。

这是自定义组件 class:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class InOutLists extends JComponent{
    GridBagConstraints gbc = new GridBagConstraints();
    JPanel backPanel, p1;
    JLabel label;
    JButton btn;

    InOutLists(){
        setBackground(new Color(51, 102, 255));
        setPreferredSize(new Dimension(100, 100));
        backPanel = new JPanel(new GridBagLayout());
        p1 = new JPanel();

        label = new JLabel("Label 1");
        btn = new JButton("Back");

        p1.add(btn);
        p1.add(label);
        gbc.gridx = 0;
        gbc.gridy = 0;

        backPanel.add(p1, gbc);
    }
}

这是主要的class:

import java.awt.Dimension;
import javax.swing.JFrame;
import java.awt.BorderLayout;

public class CCMain extends JFrame{
    CCMain(){
        super("League Management");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1080, 780);
        setPreferredSize(new Dimension(1080, 700));
        setMaximumSize(new Dimension(1080, 780));
        setVisible(true);

        InOutLists iol = new InOutLists();
        add(iol, BorderLayout.CENTER);
    }
    public static void main(String[] args) {
        new CCMain();
    }
}

如果出于某种原因您需要 backPanelp1,请使用:(请参阅注释更改)

class InOutLists extends JComponent{

    InOutLists(){
        setBackground(new Color(51, 102, 255));
        setPreferredSize(new Dimension(100, 100));
        setLayout(new FlowLayout()); //set a layout manager to JComponent
        JPanel backPanel = new JPanel(new GridBagLayout());
        JPanel p1 = new JPanel();
        JLabel label = new JLabel("Label 1");
        JButton btn = new JButton("Back");

        p1.add(btn);
        p1.add(label);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        backPanel.add(p1, gbc);

        add(backPanel);//add backPanel to JComponent
    }
}

否则,您可以将标签和按钮添加到组件中:

class InOutLists extends JComponent{

    InOutLists(){
        setBackground(new Color(51, 102, 255));
        setPreferredSize(new Dimension(100, 100));
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        JLabel label = new JLabel("Label 1");
        gbc.gridx = 0;
        gbc.gridy = 0;
        add(label, gbc);

        JButton btn = new JButton("Back");
        gbc.gridy = 1;
        add(btn, gbc);
    }
}