Java SWing——单选按钮控制背景颜色,哈哈哈,答案牛牪犇逼

该博客展示了如何使用Java Swing中的JRadioButton和ButtonGroup组件创建一个简单的颜色选择器。用户在'红色'和'绿色'两个选项中进行单选,选中的颜色将应用于指定的面板背景。程序通过匿名内部类监听按钮事件,动态改变背景色。
摘要由CSDN通过智能技术生成
package 按钮组件;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class 按钮组件单选 {
	public static void main(String[] args) {
		new MyRadio("check单选窗口");	
	}
}
class MyRadio extends JFrame{
	JRadioButton rad1,rad2;
	JPanel jp,jp2;
	ButtonGroup bg;
	public MyRadio(String title){
		super(title);
		rad1=new JRadioButton("红色");
		rad2=new JRadioButton("绿色");
		bg=new ButtonGroup();
		jp=new JPanel();
		jp2=new JPanel();
		//匿名内部类
		rad1.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				jp2.setBackground(Color.red);
			}
		});
		rad2.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				jp2.setBackground(Color.GREEN);
			}
		});
		this.add(jp2,"Center");
		bg.add(rad1);
		bg.add(rad2);
		this.add(jp,"South");
		jp.add(rad1);
		jp.add(rad2);
		jp2.setBackground(Color.WHITE);//JFrame是透明的
		this.setLocation(300, 200);//设置位置
		this.setSize(300,200);//设置大小
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//
		this.setVisible(true);//
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值