焦点事件

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;

/**
 * 多个焦点校验事件
 * */
public class SDF extends JFrame {
	private static final long serialVersionUID = 5682587455144740127L;
	private JPanel contentPane;
	private JTextField textField;
	private JTextField textField_1;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					SDF frame = new SDF();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	private Border errorBorder = BorderFactory.createLineBorder(Color.RED);
	private Border normalBorder = null;
	/**
	 * Create the frame.
	 */
	public SDF() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		textField = new JTextField();
		textField.setBounds(53, 65, 178, 21);
		contentPane.add(textField);
		textField.setColumns(10);
		normalBorder = textField.getBorder();
		textField.addFocusListener(new FocusListener() {
			JComponent c = null;
			@Override
			public void focusLost(FocusEvent e) {
				if("".equals(textField.getText().trim())){
					if(c!=null && c.getBorder() == errorBorder){
						return;
					}
					System.out.println("textfield can not null");
					textField.setBorder(errorBorder);
					textField.grabFocus();
					return;
				}else{
					textField.setBorder(normalBorder);
				}
			}
			@Override
			public void focusGained(FocusEvent e) {
				c = (JComponent) e.getOppositeComponent();
			}
		});
		
		textField_1 = new JTextField();
		textField_1.setBounds(55, 112, 179, 21);
		contentPane.add(textField_1);
		textField_1.setColumns(10);
		textField_1.addFocusListener(new FocusListener() {
			JComponent c = null;
			@Override
			public void focusLost(FocusEvent e) {
				if("".equals(textField_1.getText().trim())){
					if(c!=null && c.getBorder() == errorBorder){
						return;
					}
					textField_1.setBorder(errorBorder);
					textField_1.grabFocus();
					System.out.println("textField_1 can not null");
					return;
				}else{
					textField_1.setBorder(normalBorder);
				}
			}
			@Override
			public void focusGained(FocusEvent e) {
				c = (JComponent) e.getOppositeComponent();
			}
		});
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值