Created
August 12, 2018 12:20
-
-
Save jnizet/7ee4ccd5581820a7cd223e6bd207e6ce to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com; | |
import java.awt.*; | |
import java.awt.event.KeyAdapter; | |
import java.awt.event.KeyEvent; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
import javax.swing.*; | |
import javax.swing.event.DocumentEvent; | |
import javax.swing.event.DocumentListener; | |
public class NumberCheck extends JPanel { | |
private static final Pattern PATTERN = Pattern.compile("^(?:\\d\\s?){10}$|^(?:\\d\\s?){14}$"); | |
private JTextField txtNumberInput; | |
private JLabel errorMsg; | |
public NumberCheck() { | |
// construct the components | |
errorMsg = new JLabel("Invalid input"); | |
errorMsg.setForeground(Color.RED); | |
txtNumberInput = new JTextField(20); | |
// initialize the listeners | |
txtNumberInput.addKeyListener(new KeyAdapter() { | |
@Override | |
public void keyTyped(KeyEvent e) { | |
char c = e.getKeyChar(); | |
if ((!(Character.isDigit(c))) && (c != ' ') && (c != '\b')) { | |
e.consume(); | |
} | |
} | |
}); | |
txtNumberInput.getDocument().addDocumentListener(new DocumentListener() { | |
@Override | |
public void removeUpdate(DocumentEvent e) { | |
validateInput(); | |
} | |
@Override | |
public void insertUpdate(DocumentEvent e) { | |
validateInput(); | |
} | |
@Override | |
public void changedUpdate(DocumentEvent e) { | |
} // Not needed for plain-text fields | |
}); | |
// Add the components to the panel | |
this.setLayout(new FlowLayout()); | |
this.add(txtNumberInput); | |
this.add(errorMsg); | |
} | |
private void validateInput() { | |
String text = txtNumberInput.getText(); | |
Matcher m = PATTERN.matcher(text); | |
if (m.matches()) { | |
errorMsg.setForeground(errorMsg.getBackground()); | |
} | |
else { | |
errorMsg.setForeground(Color.RED); | |
} | |
} | |
public static void main(String[] args) { | |
SwingUtilities.invokeLater(() -> { | |
JFrame frame = new JFrame(); | |
frame.setContentPane(new NumberCheck()); | |
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
frame.pack(); | |
frame.setVisible(true); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment