⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jradiobuttondemo.java

📁 本java源程序包括了大量的学习程序(共27章)方便大家学习
💻 JAVA
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JRadioButtonDemo extends JFrame 
{
    private JPanel colorPanel, buttonPanel;
    private JRadioButton red, green, blue;
    private ButtonGroup buttonGroup;
    
	public JRadioButtonDemo() 
	{
		super("单选框");
		setSize(300, 200);		
		try
		{   // 设置外观
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		}catch(Exception e){}
		
    //获取内容面板
		Container container = getContentPane();
		
		//创建颜色面板对象
		colorPanel = new JPanel();
		colorPanel.setBackground(Color.RED);
		container.add(colorPanel, BorderLayout.CENTER);
		
		//创建单选按钮
		buttonGroup = new ButtonGroup();
		red = new JRadioButton("红色", true);
		green = new JRadioButton("绿色");
		blue = new JRadioButton("蓝色");
		
		//设置字体
		red.setFont(new Font("Serif", Font.PLAIN, 14));
		green.setFont(new Font("Serif", Font.PLAIN, 14));
		blue.setFont(new Font("Serif", Font.PLAIN, 14));
		
		buttonGroup.add(red);
		buttonGroup.add(green);
		buttonGroup.add(blue);
			
		//注册监听器
		RadioButtonHandler handler = new RadioButtonHandler();
		red.addItemListener(handler);
		blue.addItemListener(handler);
		green.addItemListener(handler);
			
		//创建存放单选按钮的面板
		buttonPanel = new JPanel();
		buttonPanel.add(red);
		buttonPanel.add(green);
		buttonPanel.add(blue);
		
		container.add(buttonPanel, BorderLayout.SOUTH);
	   		
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public static void main(String[] args) 
	{
		JRadioButtonDemo application = new JRadioButtonDemo();
	}
	
	private class RadioButtonHandler implements ItemListener
	{
		public void itemStateChanged(ItemEvent event)
		{
			if(red.isSelected())
				colorPanel.setBackground(Color.red);
			else if(green.isSelected())
				colorPanel.setBackground(Color.GREEN);
			else
				colorPanel.setBackground(Color.BLUE);
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -