Java学习之路-GUI-点击按钮改变窗口背景颜色

要求能关闭窗口、点击按钮改变窗口背景颜色。
package GUI;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class BGCUITest {

    public BGCUITest() {

        JFrame jf = new JFrame("Change BGC");
        jf.setSize(400, 400);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jf.setLocationRelativeTo(null);
        jf.setResizable(false);

        JPanel jp = new JPanel(new FlowLayout());

        JButton post = new JButton("Change");

        post.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                Random random = new Random();
                int r = random.nextInt(256);
                int g = random.nextInt(256);
                int b = random.nextInt(256);
                Color c = new Color(r, g, b);
                jf.getContentPane().setBackground(c);
                System.out.println(c);
            }
        });

        jp.add(post);
        jf.setContentPane(jp);
        jf.setVisible(true);

    }

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

}
按讚

發佈留言

電子郵件地址不會被公開。必填項已用 * 標註