Java 中的 setBounds()方法及其用途

2026-07-06 23:32:14 2268

我们的目标是了解 setBounds() 方法及其在 Java 图形用户界面 (GUI) 中的用途。我们将简要学习 setBounds(),为什么要使用它,以及如何在代码中使用它。

在 Java 中 setBounds() 方法及其的使用

在 Java 图形用户界面中,布局管理器自动决定新添加组件的大小和位置。

例如,FlowLayout 将组件添加到一行中;如果组件不适合当前行,它只会开始一个新行。

另一个例子是 BorderLayout,它在 bottom、top、right、left 和 center 中添加组件,并在中心区域留下额外的空间。

如果我们不允许使用这些布局管理器并建议手动设置组件的大小和位置,我们该怎么办?在这里,setBounds() 方法出现了。

我们使用 setBounds() 方法定义组件的边界矩形。

setBounds() 接受四个参数。前两个是用于定位组件的 x 和 y 坐标。

后两个参数是 width 和 height 用于设置组件的大小。

setBounds(int x - coordinate, int y - coordinate, int width, int height)

框架的布局管理器可以为 null 以手动设置组件的大小和位置。让我们使用下面给出的代码片段来理解这一点。

package com.setbounds.learnsetbounds;

import javax.swing.*;

public class LearnSetBounds {

public static void main(String[] args) {

JFrame jframe = new JFrame("Learning SetBounds Method");

// set the size of the window (width and height)

jframe.setSize(375, 250);

// Setting layout as null

jframe.setLayout(null);

// Creating Button

JButton jbutton = new JButton("Learning setBounds");

// Setting position and size of a button

jbutton.setBounds(80, 30, 150, 40);

// add button to the jframe

jframe.add(jbutton);

// close window on close event

jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// center the window on the computer screen

jframe.setLocationRelativeTo(null);

// show the window

jframe.setVisible(true);

}

}

输出:

将 setBound() 方法更新为 setBounds(30, 80, 150, 40); 并观察下面给出的输出。请记住,x 和 y 指定组件的 top-left 位置。

输出:

在上面给出的代码片段中,我们使用了 javax.swing.JFrame 类,它的工作方式类似于所有组件(标签、文本字段和按钮)所在的主窗口。setSize() 方法用于指定窗口的大小。

默认情况下,组件会添加到流中的单行中,如果组件不适合,则会移动到新行。FlowLayout 管理器会导致此默认行为。

由于我们要手动设置元素的大小和位置,我们需要在使用 setBound() 方法之前使用 setLayout(null)。

此外,当应用程序收到关闭窗口事件时,会调用 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)。如果用户按下窗口上的关闭 (X) 按钮,操作系统会生成 关闭窗口 事件,进一步发送到 Java 应用程序进行处理。

setVisible(true) 方法显示窗口。请记住,如果此方法获得 false 值,它也可以隐藏窗口。

此外,setLocationRelativeTo(null) 方法用于在计算机屏幕上将窗口居中。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe