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);//
}
}
Java SWing——单选按钮控制背景颜色,哈哈哈,答案牛牪犇逼
最新推荐文章于 2023-04-24 19:29:58 发布
该博客展示了如何使用Java Swing中的JRadioButton和ButtonGroup组件创建一个简单的颜色选择器。用户在'红色'和'绿色'两个选项中进行单选,选中的颜色将应用于指定的面板背景。程序通过匿名内部类监听按钮事件,动态改变背景色。
摘要由CSDN通过智能技术生成