使用java将一个面板(或JComponent)添加到另一个面板时,只有一个JComponent可见

使用java将一个面板(或JComponent)添加到另一个面板时,只有一个JComponent可见,java,swing,jframe,layout-manager,jcomponent,Java,Swing,Jframe,Layout Manager,Jcomponent,我试图使用java将一个JComponent添加到另一个组件中,但其中只有一个(顶层)是可见的。 我需要学习如何创建嵌套面板。我需要学习如何绘制面板上显示的内容 这是我的密码: import java.awt.*; import javax.swing.*; public class Main { public static void main(String[] a) { JFrame f = new JFrame(); f.setTitle("window

我试图使用java将一个JComponent添加到另一个组件中,但其中只有一个(顶层)是可见的。 我需要学习如何创建嵌套面板。我需要学习如何绘制面板上显示的内容

这是我的密码:

import java.awt.*;

import javax.swing.*;



public class Main {
   public static void main(String[] a) {
      JFrame f = new JFrame();
      f.setTitle("window");
   f.setBounds(100,50,500,300);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   MyComponent mc = new MyComponent(10, 10, 200, 200);
   MyComponent mc2 = new MyComponent(30, 30, 100, 100);
   mc.add(mc2);
   f.getContentPane().add(mc);
   f.setVisible(true);
}
static class MyComponent extends JComponent {

    private int swx;
    private int swy;
    private int nex;
    private int ney;

    public MyComponent(int swx, int swy, int nex, int ney){
        super();
        this.swx = swx;
        this.swy = swy;
        this.nex = nex;
        this.ney = ney;
    }

    public void paint(Graphics g){
        g.drawRect(swx, swy, nex, ney);
    }
}

1)
MyComponent
需要
@重写
getPreferredSize()
方法以返回适当的值。布局管理器在决定分配构件的空间量时会检查此尺寸。如果没有它(或子组件),面板或组件将返回0x0的首选大小。2) 看看有没有问题,我再也懒得去解决了。3)在任何<代码> JBase PruttCe饰件(图形G)< /C>方法,并立即调用Super方法。对于重叠的内容,考虑或BTW -你的问题是什么?