e618. Validating a JTextField When Permanently Losing the Focus

Posted borter

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了e618. Validating a JTextField When Permanently Losing the Focus相关的知识,希望对你有一定的参考价值。

This example demonstrates a text field that validates its contents when it receives a permanent focus-lost event. If the contents are invalid, it displays a modal dialog with an error message and regains the focus.

    JTextField component = new JTextField(10);
    component.addFocusListener(new MyFocusListener());
    
    public class MyFocusListener extends FocusAdapter {
        boolean showingDialog = false;
    
        public void focusGained(FocusEvent evt) {
            final JTextComponent c = (JTextComponent)evt.getSource();
            String s = c.getText();
    
            // Position the caret at the 1st non-digit character
            for (int i=0; i<s.length(); i++) {
                // Ensure validity
                if (!Character.isDigit(s.charAt(i))) {
                    c.setSelectionStart(i);
                    c.setSelectionEnd(i);
                    break;
                }
            }
        }
        public void focusLost(FocusEvent evt) {
            final JTextComponent c = (JTextComponent)evt.getSource();
            String s = c.getText();
    
            if (evt.isTemporary()) {
                return;
            }
            for (int i=0; i<s.length(); i++) {
                // Ensure validity
                if (!Character.isDigit(s.charAt(i))) {
                    // Find top-level window
                    Component par = c;
                    while (par.getParent() != null) {
                        par = par.getParent();
                    }
                    final Frame frame = (Frame)par;
    
                    // Create and display an error message
                    JOptionPane optionPane = new JOptionPane("The value must only contain digits",
                        JOptionPane.ERROR_MESSAGE, JOptionPane.DEFAULT_OPTION);
                    optionPane.createDialog(frame, null).show();
    
                    // Regain the focus
                    c.requestFocus();
                    break;
                }
            }
        }
    }

 

Related Examples

以上是关于e618. Validating a JTextField When Permanently Losing the Focus的主要内容,如果未能解决你的问题,请参考以下文章

需要不同签名的两个事件的相同事件处理程序

Eclipse Validating比较慢,去掉Validating

eclipse validating 卡着一直不动

今日只为你狂欢-----JAVA线程总结(零基础入门)

edai组成啥单词?

Eclipse Validating缓慢的优化