Swing-setBounds()用法-入門


先看API:

public void setBounds(Rectangle r)

移動組件並調整其大小,使其符合新的有界矩形 r。由 r.x 和 r.y 指定組件的新位置,由 r.width 和 r.height 指定組件的新大小 

參數: r - 此組件的新的有界矩形

從API來看,該方法的作用相當於setLocation()與 setSize()的總和。在實際使用時,需將容器的layout設置為null,因為使用布局管理器時,控件的位置與尺寸是由布局管理器來分配的。需要注意的是,這時必須手動指定容器的尺寸,因為空的布局管理器會將容器自身的PreferredSize清零,導致容器無法在GUI上顯示。因此,如果容器在上級容器中使用布局管理器排列,那么需使用setPreferredSize(),如果容器在上級容器中仍然手動排列,那么對容器使用setBounds()即可。下面是測試demo:

 

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);
    }
}

運行效果如下:

運行效果圖

程序輸出如下:

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]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM