📄 randcolorbackground.java
字号:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class RandColorBackground extends JxFrame implements ActionListener {
private JButton Change;
private Color color;
private JPanel jp;
public RandColorBackground() {
super("随机改变背景颜色");
color = Color.yellow;
setGUI();
}
private void setGUI() {
jp = new JPanel();
getContentPane().add(jp);
Change = new JButton("改变颜色");
Change.addActionListener(this);
jp.add(Change);
setSize(new Dimension(250, 100));
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if (obj == Change)
switchcolors();
}
private void switchcolors() {
// 颜色中的RGB和Alpha通道的值的范围为0-255
int Max = 255;
int Min = 0;
// 随机赋值
int R = Min + (int) ((Max - Min) * Math.random());
int G = Min + (int) ((Max - Min) * Math.random());
int B = Min + (int) ((Max - Min) * Math.random());
int A = Min + (int) ((Max - Min) * Math.random());
// 在控制台输出值
System.out.println("Color Changed: ");
System.out.println("R = " + R);
System.out.println("G = " + G);
System.out.println("B = " + B);
System.out.println("A = " + A);
// 利用RGBA产生新的颜色
color = new Color(R, G, B, A);
jp.setBackground(color);
repaint();
}
public static void main(String[] args) {
new RandColorBackground();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -