Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Tầm quan trọng của OverlayLayout trong Java

OverlayLayout

  • OverlayLayout là một lớp con của Object và sắp xếp các thành phần chồng lên nhau, dùng alignment được chỉ định để định vị tương đối.
  • Khi các kích thước khác nhau được cho các thành phần, chúng ta có thể thấy tất cả các thành phần.
  • Để căn chỉnh thành phần chồng lên nhau hoặc bất kỳ đâu trong frame, dùng hai phương thức setAlignmentX() và setAlignmentY(). Tham số là giá trị float từ 0.0f đến 1.0f. OverlayLayout lấy tối đa 1.0f mặc định.
  • Các phương thức quan trọng: addLayoutComponent(), getTarget(), invalidateLayout(), maximumLayoutSize() v.v.

Ví dụ

import java.awt.*;
import javax.swing.*;
import javax.swing.OverlayLayout;

public class OverlayLayoutTest extends JFrame {
    public OverlayLayoutTest() {
        setTitle("OverlayLayout Test");
        JPanel panel = new JPanel() {
            public boolean isOptimizedDrawingEnabled() {
                return false;
            }
        };
        LayoutManager overlay = new OverlayLayout(panel);
        panel.setLayout(overlay);
        JButton button = new JButton("Small");
        button.setMaximumSize(new Dimension(75, 50));
        button.setBackground(Color.white);
        panel.add(button);
        button = new JButton("Medium Btn");
        button.setMaximumSize(new Dimension(125, 75));
        button.setBackground(Color.lightGray);
        panel.add(button);
        button = new JButton("Large Button");
        button.setMaximumSize(new Dimension(200, 100));
        button.setBackground(Color.orange);
        panel.add(button);
        add(panel, BorderLayout.CENTER);
        setSize(400, 300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String args[]) {
        new OverlayLayoutTest();
    }
}

Kết quả

Tầm quan trọng của OverlayLayout trong Java