import java.awt.*;
import javax.swing.*;public class MyComponent extends JComponent{
        Panel pane;         public  void addComponentsToPane() {
            Panel pane = new Panel();pane.setVisible(true);
            Panel p1, p2 ;
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
p1 = new  Panel ();p1.setBackground(Color.pink); p1.setVisible(true);         c.gridx = 0;     c.gridy = 0;
              c.weightx = 1;c.weighty = 1;
            
              c.ipadx= 0;c.ipady=0;c.fill = GridBagConstraints.BOTH;
    pane.add(p1, c);    p2= new  Panel ();p2.setBackground(Color.red); p2.setVisible(true);
  
    c.gridx = 3;     c.gridy = 0;
            c.weightx = 0.3;c.weighty = 0.3;
    c.ipadx= 0;c.ipady=0;            pane.add(p2, c);

    }
          MyComponent(){
                 super(); addComponentsToPane() ;
                                
                  setVisible(true);
                 }
           public static void main (String args[]) {
               JFrame f = new JFrame();
              MyComponent mc = new MyComponent();
              f.getContentPane().add(mc);f.setVisible(true);
           }
}

解决方案 »

  1.   

    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    JFrame f = new JFrame();
                                   MyComponent mc = new MyComponent();
                                   f.getContentPane().add(mc);
                                   f.setVisible(true);
    }
    });
    }
      

  2.   

    import java.awt.*;
    import javax.swing.*;public class MyComponent extends JComponent {
    Panel pane; public void addComponentsToPane() {
    Panel pane = new Panel();
    pane.setVisible(true);
    Panel p1, p2;
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    p1 = new Panel();
    p1.setBackground(Color.pink);
    p1.setVisible(true); c.gridx = 0;
    c.gridy = 0;
    c.weightx = 1;
    c.weighty = 1; c.ipadx = 0;
    c.ipady = 0;
    c.fill = GridBagConstraints.BOTH;
    pane.add(p1, c); p2 = new Panel();
    p2.setBackground(Color.red);
    p2.setVisible(true); c.gridx = 3;
    c.gridy = 0;
    c.weightx = 0.3;
    c.weighty = 0.3;
    c.ipadx = 0;
    c.ipady = 0; pane.add(p2, c); } MyComponent() {
    super();
    addComponentsToPane(); setVisible(true);
    } public static void main(String args[]) {
    JFrame f = new JFrame();
    MyComponent mc = new MyComponent();
    f.getContentPane().add(mc);
    f.setBounds(100,200,400,500);//没有设定大小。。
    f.setVisible(true);

    }
    }
      

  3.   

     public static void main(String args[]) {
            JFrame f = new JFrame();
            MyComponent mc = new MyComponent();
            f.getContentPane().add(mc);
            f.setSize(400,500);//没有设定大小。。
            f.setVisible(true);
            
        }
      

  4.   

    f.setSize(400,500);
    这句没用,好像还要重写什么方法的