焦点事件

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

 

你可能感兴趣的:(事件)