JFrame 默认布局是 BorderLayout,它内部是拉伸组件填充的你可以修改布局为 FlowLayout 或中间插入一个 JPanel “缓冲”

解决方案 »

  1.   

    在添加组件前先去掉JFrame的默认布局。即在
    getContentPane().add(....)前加入一句getContentPane().setLayout(null);
    以后即可。
      

  2.   

    我用了null不要布局了,还不好使吗?
    jpanel,这个。import java.awt.*;
    import javax.swing.*;
    public class test extends JFrame{
      public test(){
        JPanel jPanel=new JPanel();
        jPanel.add(new QiZi(200,200));
        getContentPane().add(jPanel);
        setBounds(300,120,400,300);
        show();
      }
      class QiZi extends JComponent {
        QiZi(int x,int y) {
          setSize(30, 30);
          setLocation( x, y);
          setBackground(Color.blue);
          setBorder(BorderFactory.createRaisedBevelBorder());
        }
      }
      public static void main (String[] args){
        new test();
      }
    }
    我这么改对么??
      

  3.   

    getContentPane().add( new QiZi(200,200),null);
    里的null是控制什么的?
    我还以为是布局为null?
      

  4.   

    没搞错吧JComponent是一个抽象类,它扩展自Container啊
    看清楚一下文档吧:
    public abstract class JComponent extends Container implements SerializableThe base class for all Swing components except top-level containers. To use a component that inherits from JComponent, you must place the component in a containment hierarchy whose root is a top-level Swing container. Top-level Swing containers -- such as JFrame, JDialog, and JApplet -- are specialized components that provide a place for other Swing components to paint themselves. For an explanation of containment hierarchies, see Swing Components and the Containment Hierarchy, a section in The Java Tutorial.是所有Swing组件的基类!
    Swing当中的JRootPane都是从JComponent继承来的!
    public class JRootPane extends JComponent implements Accessible//JApplet和JFrame都是只包含一个组件的容器,即JRootPane的一个实例,JRootPane包含一个称作内容窗格的容器
    //内容窗格包含了与特定的小应用程序和应用程序有关的所有内容,即包含在当中的组件。
    //千万记住:我们只应当为内容窗格设置布局管理器,而不是直接为Swing小应用程序或应用程序设置布局管理器
    //这个与AWT的布局管理器是不一样的。
      

  5.   

    我又无知了,我“直接为Swing小应用程序或应用程序设置布局管理器”了???
    我的那个是“AWT的布局管理器”?
    刚学java,不好意思...
      

  6.   

    改成这样:
    import java.awt.*;
    import javax.swing.*;
    public class test extends JFrame{
      public test(){
        getContentPane().setLayout(null);   //这一行!
        getContentPane().add( new QiZi(200,200));
        setBounds(300,120,400,300);
        show();
      }
      class QiZi extends JComponent {
        QiZi(int x,int y) {
          setSize(30, 30);
          setLocation( x, y);
          setBackground(Color.blue);
          setBorder(BorderFactory.createRaisedBevelBorder());
        }
      }
      public static void main (String[] args){
        new test();
      }
    }
      

  7.   

    谢谢,我照你上面提示的已经修改成功了,可我还有两个问题:
    1.原来的 
    getContentPane().add( new QiZi(200,200),null);
    中的null是干么的??
    2.用jpanel正确的写法是什么?
    谢谢大家