12.单选按钮

效果:

原始:

点击Metal:

点击Motif:

点击Windows:

单击Hello, World:

package com.lvshitech.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

@SuppressWarnings("serial")
public class JRadioButtonDemo extends JPanel {
	static JFrame frame;
	static String metal = "Metal";
	static String motif = "Motif";
	static String windows = "Windows";
	JRadioButton metalButton, motifButton, windowsButton;
	
	public JRadioButtonDemo() {
		// 普通按钮
		JButton button = new JButton("Hello, World");
		button.setMnemonic('h');		// 给指定字符添加下划线
		
		// metalButton
		metalButton = new JRadioButton(metal);
		metalButton.setMnemonic('m');
		metalButton.setActionCommand(metal);
		
		// motifButton
		motifButton = new JRadioButton(motif);
		motifButton.setMnemonic('m');
		motifButton.setActionCommand(motif);
		
		// windowsButton
		windowsButton = new JRadioButton(windows);
		windowsButton.setMnemonic('w');
		windowsButton.setActionCommand(windows);
		
		// 将单选按钮设置为一组
		ButtonGroup buttonGroup = new ButtonGroup();
		buttonGroup.add(metalButton);
		buttonGroup.add(motifButton);
		buttonGroup.add(windowsButton);
		
		// 对单选按钮设置监听器(这个监听器是自定义的类)
		RadioListener radioListener = new RadioListener();
		button.addActionListener(radioListener);
		metalButton.addActionListener(radioListener);
		motifButton.addActionListener(radioListener);
		windowsButton.addActionListener(radioListener);
		
		// 添加到容器
		add(button);
		add(metalButton);
		add(motifButton);
		add(windowsButton);
	}
	
	/** ActionListener监听器监听单选按钮 */
	class RadioListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			// 定义事件
			if (e.getActionCommand().equals(metal)) {
				frame.setSize(400, 100);
			} else if (e.getActionCommand().equals(motif)) {
				frame.setSize(500, 150);
			} else if (e.getActionCommand().equals(windows)) {
				frame.setSize(600, 200);
			} else {
				frame.pack();
			}
		}
	}
	
	public static void main(String[] args) {
		JRadioButtonDemo panel = new JRadioButtonDemo();
		frame = new JFrame("使用JRadioButton选择观感");
		frame.getContentPane().add("Center", panel);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}
}

 

posted @ 2018-01-13 00:15  半生戎马,共话桑麻、  阅读(184)  评论(0)    收藏  举报
levels of contents