51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

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(); }

}


赞(1)
未经允许不得转载:工具盒子 » Java学习之路-GUI-点击按钮改变窗口背景颜色