【设计一个单选颜色框】

题目:设计一个界面,有四个单选按钮和一个文本框,当单击按钮时,文本框显示对应文字,并且背景颜色变为相应的颜色。(来自《JAVA程序设计》第11章课后习题)

涉及到:单选框的实现,设计文本框颜色,设计按钮组

效果图:

 

 代码及注释:

package shiYan_15;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class dxk extends JFrame implements ActionListener{
	private JRadioButton b1,b2,b3,b4;
	private JTextField jtx;
	public dxk()
	{
		setBounds(300,200,400,300);//前两个代表Location()中的位置,后两个代表Size()中的宽和高,这样一句话就可以代替写setLocation()和setSize()两句话了
		setTitle("单选颜色框");
		setLayout(new FlowLayout(FlowLayout.CENTER));
		b1=new JRadioButton("红色");
		b2=new JRadioButton("蓝色");
		b3=new JRadioButton("绿色");
		b4=new JRadioButton("黄色");
		ButtonGroup bp=new ButtonGroup();//创建按钮组,将按钮添加到一个按钮组中,就可以实现功能:一组中只选其一,选其他按钮时自动取消之前的选择
		bp.add(b1);
		bp.add(b2);
		bp.add(b3);
		bp.add(b4);
		add(b1);
		add(b2);
		add(b3);
		add(b4);
		jtx=new JTextField(20);
		b1.addActionListener(this);
		b2.addActionListener(this);
		b3.addActionListener(this);
		b4.addActionListener(this);
		add(jtx);
		setVisible(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	public void actionPerformed(ActionEvent e)
	{
		if(e.getSource()==b1) {
			jtx.setText("红色");
			jtx.setBackground(Color.RED);
		}else if(e.getSource()==b2) {
			jtx.setText("蓝色");
			jtx.setBackground(Color.BLUE);
		}else if(e.getSource()==b3) {
			jtx.setText("绿色");
			jtx.setBackground(Color.GREEN);
		}else if(e.getSource()==b4) {
			jtx.setText("黄色");
			jtx.setBackground(Color.YELLOW);
		}
	}
	public static void main(String[] args) {
		new dxk();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

迎风809

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

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

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

打赏作者

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

抵扣说明:

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

余额充值