Java 中 setBounds() 方法有什麼作用?


佈局管理器 用於自動決定新增元件的位置和大小。在沒有佈局管理器的情況下,必須手動設定元件的位置和大小。setBounds() 方法用於在這種情況下設定位置和大小。要手動指定元件的位置和大小,框架的佈局管理器可以設定為 null

setBounds()

setBounds() 方法需要四個引數。前兩個引數是元件左上角xy 座標,第三個引數是元件的寬度,第四個引數是元件的高度

語法

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

輸出

更新於: 2023年9月13日

35K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告