【设计一个单选颜色框】

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

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

效果图:

【设计一个单选颜色框】_第1张图片

【设计一个单选颜色框】_第2张图片

 

 代码及注释:

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();
	}

}

你可能感兴趣的:(Java,java,jvm,开发语言)