扩展JPanels的问题

嗨,我正在解决一个问题,我在Swing中遇到了一些问题。 使用扩展JFrame或JComponent的类没有任何问题,但是当我尝试使用我编写的扩展JPanel的类时,它将不会显示,并且我在该面板上调用的任何内容都不显示,包括添加自定义JComponents到它。 创建JPanel扩展类然后将其设置为要在JFrame中使用的内容窗格的一般过程是什么?

我(我的个人观点)看不出将JComponent扩展为JComponentJPanelJLabel ,更多inheritance与组合 ,例如

 import java.awt.*; import javax.swing.*; public class CustomComponent extends JFrame { private static final long serialVersionUID = 1L; public CustomComponent() { setTitle("Custom Component Test"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(new CustomComponents()); pack(); setMinimumSize(getSize());// enforces the minimum size of both frame and component setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { CustomComponent main = new CustomComponent(); //main.display(); } }); } } class CustomComponents extends JComponent { private static final long serialVersionUID = 1L; @Override public Dimension getMinimumSize() { return new Dimension(100, 100); } @Override public Dimension getPreferredSize() { return new Dimension(400, 300); } @Override public void paintComponent(Graphics g) { int margin = 10; Dimension dim = getSize(); super.paintComponent(g); g.setColor(Color.red); g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2); } } 

你应该添加你的类,将Jpanel扩展到像JFrame.A这样扩展JPanel的类,它不会显示任何东西,因为它不是容器。