⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 e618. validating a jtextfield when permanently losing the focus.txt

📁 这里面包含了一百多个JAVA源文件
💻 TXT
字号:
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;
                }
            }
        }
    }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -