Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

การใช้งานเมธอด setBounds() ใน Java

Layout Managers ใช้ quyết địnhตำแหน่งและขนาดคอมโพเนนต์อัตโนมัติ หากไม่มี Layout Manager ต้องตั้งค่าตำแหน่งและขนาดเอง เมธอด setBounds() ใช้ในสถานการณ์นี้ ต้องตั้ง Layout Manager ของ Frame เป็น null

setBounds()

เมธอด setBounds() ต้องการ 4 อาร์กิวเมนต์: อาร์กิวเมนต์ 2 ตัวแรกคือ พิกัด x และ y ของ มุมซ้ายบน ของคอมโพเนนต์ ตัวที่ 3 คือ ความกว้าง ตัวที่ 4 คือ ความสูง

ไวยากรณ์

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);
        // ตั้ง Layout เป็น null
        frame.setLayout(null);
        // สร้างปุ่ม
        JButton button = new JButton("Hello Java");
        // ตั้งตำแหน่งและขนาดปุ่ม
        button.setBounds(80, 30, 120, 40);
        frame.add(button);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

ผลลัพธ์

การใช้งานเมธอด setBounds() ใน Java