Java setBounds()方法有什么用途
布局管理器被用于自动决定添加组件的位置和大小。在没有布局管理器的情况下,组件的位置和大小必须手动设置。在这种情况下,setBounds()方法可以用来设置位置和大小。要手动指定组件的位置和大小,可以将帧的布局管理器设置为null。
setBounds()
setBounds()方法需要四个参数。前两个参数是组件左上角的x和y坐标,第三个参数是组件的宽度,第四个参数是组件的高度。
语法
setBounds(int x-coordinate, int y-coordinate, int width, int height)
示例
import javax.swing.*;
import java.awt.*;
public class SetBoundsTest {
public static void main(String arg[]) {
JFrame frame = new JFrame("SetBounds Method Test");
frame.setSize(375, 250);
// Setting layout as null
frame.setLayout(null);
// Creating Button
JButton button = new JButton("Hello Java");
// Setting position and size of a button
button.setBounds(80,30,120,40);
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}