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

运行效果如下:

Swing-setBounds()用法-入门-LMLPHP

运行效果图

程序输出如下:

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]

04-18 02:45
查看更多