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

Cách thiết lập màu nền cho JPanel trong Java

JPanel là một container và là thành phần vô hình trong Java. FlowLayout là layout mặc định cho JPanel. Ta có thể thêm hầu hết các component như button, text field, label, table, list, tree vào JPanel. Ta thiết lập màu nền cho JPanel bằng phương thức setBackground().

Ví dụ

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

public class JPanelBackgroundColorTest extends JFrame {
    private JPanel panel;

    public JPanelBackgroundColorTest() {
        setTitle("JPanelBackgroundColor Test");
        panel = new JPanel();
        panel.add(new JLabel("Welcome to Tutorials Point"));
        panel.setBackground(Color.green);
        add(panel, BorderLayout.CENTER);
        setSize(375, 250);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

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

Kết quả

Cách thiết lập màu nền cho JPanel trong Java