Java——JRadioButton单选按钮的使用例子

┏(ω)=☞ 本专栏的目录(为您提供更好的查询方式)(点这里说不定有你想要的)

代码示例


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class a extends JFrame implements ActionListener{
	public static void main(String[] args) {
		new a();
	}

	JLabel JL1 = new JLabel ("用户名:");
	JLabel JL2  = new JLabel ("密码    :");
	JComboBox JC = new JComboBox(new String[] {"123","456"});
	JPasswordField JP1 = new JPasswordField(10);
	JButton JB1 = new JButton("确定");
	JButton JB2 = new JButton("取消");
	JRadioButton JR1 =new JRadioButton("用户登陆");//创建单选按钮
	JRadioButton JR2 =new JRadioButton("管理员登陆");//创建单选按钮
	ButtonGroup BG=new ButtonGroup(); //创建按钮组

	public a() {
		JPanel JP = (JPanel) this.getContentPane();
		JP.setLayout(new GridLayout(4,2,10,10));//设置网格布局四行二列上下左右间距为十

		JB1.addActionListener(this);
		JB2.addActionListener(this);

		BG.add(JR1);
		BG.add(JR2);
		JP.add(JL1);
		JP.add(JC);
		JP.add(JL2);
		JP.add(JP1);
		JP.add(JR1);
		JP.add(JR2);
		JP.add(JB1);
		JP.add(JB2);

		this.setSize(300,200);//设置窗口大小
		this.setLocationRelativeTo(null);//窗口居中
		this.setVisible(true);//窗口可见
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);//设置关闭模式
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==JB1) {//是否点击JB1按钮
			if(JR1.isSelected()) {//是否选择了单选按钮的"用户登陆"
				if(JC.getSelectedItem().equals("123") && JP1.getText().equals("123")) 
					JOptionPane.showMessageDialog(this,"欢迎您,用户"+JC.getSelectedItem()+"登陆成功");
				else 
					JOptionPane.showMessageDialog(this, "用户名或密码错误");
			}
			else if(JR2.isSelected()) {//是否选择了单选按钮的"管理员登陆"
				if(JC.getSelectedItem().equals("456") && JP1.getText().equals("456")) 
					JOptionPane.showMessageDialog(this,"欢迎您,管理员"+JC.getSelectedItem()+"登陆成功");
				else 
					JOptionPane.showMessageDialog(this, "用户名或密码错误");
			}
		}
		if(e.getSource()==JB2) {//是否点击JB2按钮"取消"按钮
			System.exit(0);//关闭窗口
		}
	}
}


图例

在这里插入图片描述

  • 10
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

桂?

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值