天天看點

Box容器中的"剛性區域"概念

該例是為了學習剛性區域的用法.

(1)Box4.java

import javax.swing.*;

import java.awt.*;

public class Box4 extends JApplet

{

    public void init()

    {

       Box bv=Box.createVerticalBox();

       bv.add(new JButton("Top"));

       bv.add(Box.createRigidArea(new Dimension(120,90)));

       bv.add(new JButton("Bottom"));

       Box bh=Box.createHorizontalBox();

       bh.add(new JButton("Left"));

       bh.add(Box.createRigidArea(new Dimension(160,80)));

       bh.add(new JButton("Right"));

       bv.add(bh);

       getContentPane().add(bv);

    }

    public static void main(String[] args)

    {

       Console.run(new Box4(),450,300);

    }

}

(2)Console.java

import javax.swing.*;

public class Console

{

   public static String title(Object o)

   {

      String t=o.getClass().toString();

      if(t.indexOf("class")!=-1)

      {

          t=t.substring(6);

      }

      return t;

   }

   public static void run(JFrame frame,int width,int height)

   {

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      frame.setSize(width,height); 

      frame.setVisible(true);

   }

   public static void run(JApplet applet,int width,int height)

   {

      JFrame frame=new JFrame(title(applet));

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      frame.getContentPane().add(applet);

      frame.setSize(width,height);  

      applet.init();

      applet.start();

      frame.setVisible(true);

   }

   public static void run(JPanel panel,int width,int height)

   {

      JFrame frame=new JFrame(title(panel));

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      frame.getContentPane().add(panel);

      frame.setSize(width,height);   

      frame.setVisible(true);

   }

}

注意:"剛性區域"使用了絕對值,是以有人認為這麼做帶來的問題比帶來的好處更多,

是以,要慎用。