zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Spark SQL+day04笔记
    Spark 环境搭建
    海量数据处理 算法总结2
    Scala面试题 看过1
    HTML-table、form表单标签的介绍
    Java-CSS美化网页元素
    Java-BOM与DOM对象
    java-CSS盒子模型、浮动、定位
    java-基础面试题(2)
    Java-io流
  • 原文地址:https://www.cnblogs.com/borter/p/9596104.html
Copyright © 2011-2022 走看看