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

Cách thu nhỏ/phóng to JFrame lập trình trong Java

JFrame là một lớp con của Frame và các thành phần thêm vào frame được gọi là nội dung (contents), được quản lý bởi contentPane. JFrame chứa cửa sổ với tiêu đề, viền, (tùy chọn) menu bar và thành phần riêng của người dùng. Mặc định, chúng ta thu nhỏ JFrame bằng nút minimize và phóng to bằng nút maximize ở góc trên bên phải. Chúng ta cũng có thể làm lập trình bằng setState(JFrame.ICONIFIED) để thu nhỏ và setExtendedState(JFrame.MAXIMIZED_BOTH) để phóng to JFrame.

Ví dụ

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

public class JFrameIconifiedTest extends JFrame implements ActionListener {
    private JButton iconifyButton, maximizeButton;

    public JFrameIconifiedTest() {
        setTitle("JFrameIconified Test");
        iconifyButton = new JButton("JFrame Iconified");
        add(iconifyButton, BorderLayout.NORTH);
        iconifyButton.addActionListener(this);
        maximizeButton = new JButton("JFrame Maximized");
        add(maximizeButton, BorderLayout.SOUTH);
        maximizeButton.addActionListener(this);
        setSize(400, 275);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource().equals(iconifyButton)) {
            setState(JFrame.ICONIFIED); // Thu nhỏ frame
        } else if (ae.getSource().equals(maximizeButton)) {
            setExtendedState(JFrame.MAXIMIZED_BOTH); // Phóng to frame
        }
    }

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

Kết quả

Cách thu nhỏ/phóng to JFrame lập trình trong Java

Trong chương trình trên, nếu click "JFrame Iconified", frame thu nhỏ; click "JFrame Maximized", frame phóng to.