码迷,mamicode.com
首页 > 其他好文 > 详细

e618. Validating a JTextField When Permanently Losing the Focus

时间:2018-09-06 10:57:10      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:selection   rar   frame   cin   character   position   ext   created   rman   

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

标签:selection   rar   frame   cin   character   position   ext   created   rman   

原文地址:https://www.cnblogs.com/borter/p/9596104.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!