java编写一个窗体应用,点击按钮让按钮的背景颜色随机变化。

题目: 编写一个窗体应用,点击按钮让按钮的背景颜色随机变化。

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*; //JFrame是swing的框架类

public class gui extends JFrame{ //继承JFrame
	//定义一个方法
	public void aa(String title) {
		
		JFrame a = new JFrame(title);
		a.setSize(400,300);//设置窗口大小
		a.setVisible(true);//使窗体可视
		a.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//设置窗体关闭方式
		
		Container bb = a.getContentPane();//将窗体转化为容器容器
		
		bb.setBackground(Color.yellow);//设置窗口背景色
		
		
		JButton button = new JButton("按钮");
		bb.add(button);//添加按钮到容器中
		button.setBounds(100, 100, 100, 80);//设置按钮大小
		
		
		
		button.addActionListener(new ActionListener() {//按钮响应事件
			public void actionPerformed(ActionEvent e) {
				
				Random rd=new Random();
                int r=rd.nextInt(255);
                int g=rd.nextInt(255);
                int b=rd.nextInt(255);
                Color color=new Color(r,g,b);
                button.setBackground(color);
                
			}
		});
		
	}
	
	public static void main(String arge[]) {
		new gui().aa("按钮");
		
	}
}

运行截图如下:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44797539/article/details/105909242