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
  • 相关阅读:
    [官网]清华大学的开源镜像站点 配置方法
    Android MIFARE NFCA源码解析
    Delphi XE8 TStyleBook的使用
    【FireMonkey】StyleBook使用方法
    Delphi第三方组件安装DCU.PAS.DPK.BPL.ActiveX控件
    M1卡说明及使用proxmark3破解方法
    M1卡修改各区块控制位值和数据
    DICOMDIR
    ZentaoPMS 系统的优先级以及修改
    集成禅道和svn
  • 原文地址:https://www.cnblogs.com/borter/p/9596104.html
Copyright © 2011-2022 走看看