java GUI 事件 文本框焦点事件 FocusListener

/*

三个文本框 哪个文本框获得了焦点就将背景设置为红色 文本设置为文本框获得了焦点

*/

import java.awt.Color;

import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;


import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;


public class FocusEventDemo extends JFrame implements FocusListener{
	private JTextField tUser, tID, tPW;
	public FocusEventDemo() {
		JLabel User = new JLabel("用户名", JLabel.CENTER);
		JLabel ID = new JLabel("身份证号", JLabel.CENTER);
		JLabel PW = new JLabel("密码", JLabel.CENTER);
		tUser = new JTextField(10);
		tID = new JTextField(20);
		tPW = new JTextField(25);
		User.setFont(new Font("Dialog", Font.PLAIN, 20));
		ID.setFont(new Font("Dialog", Font.PLAIN, 20));
		PW.setFont(new Font("Dialog", Font.PLAIN, 20));

		setLayout(new GridLayout(3, 2));
		add(User);
		add(tUser);
		add(ID);
		add(tID);
		add(PW);
		add(tPW);

		tUser.addFocusListener(this);
		tID.addFocusListener(this);
		tPW.addFocusListener(this);

	}

	@Override
	public void focusGained(FocusEvent e) {
		JComponent component = (JComponent)e.getSource();
		if(component==tUser) {
			tUser.setText("文本框获得了焦点");
			tUser.setBackground(Color.white);
		}else if(component==tID) {
			tID.setText("文本框获得了焦点");
			tID.setBackground(Color.white);
		}else if(component==tPW) {
			tPW.setText("文本框获得了焦点");
			tPW.setBackground(Color.white);
		}

	}

	@Override
	public void focusLost(FocusEvent e) {
		JComponent component = (JComponent)e.getSource();
		if(component==tUser) {
			tUser.setText("");
			tUser.setBackground(Color.RED);
		}else if(component==tID) {
			tID.setText("");
			tID.setBackground(Color.RED);
		}else if(component==tPW) {
			tPW.setText("");
			tPW.setBackground(Color.RED);
		}
	}

	public static void main(String[] args) {
		FocusEventDemo ft = new FocusEventDemo();
		ft.pack();
		ft.setLocationRelativeTo(null);
		ft.setResizable(false);
		ft.setVisible(true);
		ft.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

}

  • 6
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值