先看API:html
public void setBounds(Rectangle r)java
移動組件並調整其大小,使其符合新的有界矩形 r。由 r.x 和 r.y 指定組件的新位置,由 r.width 和 r.height 指定組件的新大小 佈局
參數: r - 此組件的新的有界矩形測試
從API來看,該方法的做用至關於setLocation()與 setSize()的總和。在實際使用時,需將容器的layout設置爲null,由於使用佈局管理器時,控件的位置與尺寸是由佈局管理器來分配的。須要注意的是,這時必須手動指定容器的尺寸,由於空的佈局管理器會將容器自身的PreferredSize清零,致使容器沒法在GUI上顯示。所以,若是容器在上級容器中使用佈局管理器排列,那麼需使用setPreferredSize(),若是容器在上級容器中仍然手動排列,那麼對容器使用setBounds()便可。下面是測試demo:spa
import java.awt.Dimension; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /* * 2015-06-14 */ public class setBoundsDemo { public static void main(String[] args) { // TODO Auto-generated method stub //設置panel的layout以及sieze JPanel jpanel = new JPanel(); System.out.println("default PreferredSize is " + jpanel.getPreferredSize()); System.out.println("default Size is " + jpanel.getSize()); jpanel.setLayout(null); System.out.println("In null layout, the PreferredSize is " + jpanel.getPreferredSize()); System.out.println("In null layout, the Size is " + jpanel.getSize()); jpanel.setPreferredSize(new Dimension(400, 400)); //添加按鈕 JButton button11 = new JButton("setBounds"); JButton button12 = new JButton("setLocationAndSetSize"); button11.setBounds(20, 20, 100, 100); button12.setLocation(250, 250); button12.setSize(100, 100); jpanel.add(button11); jpanel.add(button12); // 設置窗體屬性 JFrame frame = new JFrame("setBoundsDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(jpanel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
運行效果以下:code
運行效果圖htm
程序輸出以下:blog
default PreferredSize is java.awt.Dimension[width=10,height=10]
default Size is java.awt.Dimension[width=0,height=0]
In null layout, the PreferredSize is java.awt.Dimension[width=0,height=0]
In null layout, the Size is java.awt.Dimension[width=0,height=0]文檔