1 | package org.greenstone.gatherer.gui;
|
---|
2 |
|
---|
3 | import java.awt.*;
|
---|
4 | import java.util.regex.*;
|
---|
5 | import javax.swing.*;
|
---|
6 | import javax.swing.event.*;
|
---|
7 | import javax.swing.text.*;
|
---|
8 |
|
---|
9 | public class EmailField
|
---|
10 | extends JTextField
|
---|
11 | implements DocumentListener {
|
---|
12 |
|
---|
13 | static final public Pattern EMAIL_PATTERN = Pattern.compile("([^()\\-<> @,;:\"][^()<> @,;:\"]*|\"[^()<>@,;:\"]+\")@([A-Za-z](-*[A-Za-z0-9])*(\\.[A-Za-z](-*[A-Za-z0-9])*)*)");
|
---|
14 |
|
---|
15 | private boolean invalid = false;
|
---|
16 | private Color background;
|
---|
17 | private Color invalid_background;
|
---|
18 |
|
---|
19 | public EmailField(Color invalid_background) {
|
---|
20 | super();
|
---|
21 | this.invalid_background = invalid_background;
|
---|
22 | }
|
---|
23 |
|
---|
24 | public EmailField(String email, Color invalid_background) {
|
---|
25 | super(email);
|
---|
26 | this.invalid_background = invalid_background;
|
---|
27 | }
|
---|
28 |
|
---|
29 | /** Gives notification that an attribute or set of attributes changed.
|
---|
30 | * @param e
|
---|
31 | */
|
---|
32 | public void changedUpdate(DocumentEvent e) {
|
---|
33 | validateEmail();
|
---|
34 | }
|
---|
35 |
|
---|
36 | /** Gives notification that there was an insert into the document.
|
---|
37 | * @param e
|
---|
38 | */
|
---|
39 | public void insertUpdate(DocumentEvent e) {
|
---|
40 | validateEmail();
|
---|
41 | }
|
---|
42 |
|
---|
43 | /** Gives notification that a portion of the document has been removed.
|
---|
44 | * @param e
|
---|
45 | */
|
---|
46 | public void removeUpdate(DocumentEvent e) {
|
---|
47 | validateEmail();
|
---|
48 | }
|
---|
49 |
|
---|
50 | private void validateEmail() {
|
---|
51 | Matcher m = EMAIL_PATTERN.matcher(getText());
|
---|
52 | if(m.matches()) {
|
---|
53 | // It was invalid, but now its valid again
|
---|
54 | if(invalid) {
|
---|
55 | setBackground(background);
|
---|
56 | invalid = false;
|
---|
57 | }
|
---|
58 | // Otherwise nothings changed so why do anything
|
---|
59 | }
|
---|
60 | else {
|
---|
61 | background = getBackground();
|
---|
62 | setBackground(invalid_background);
|
---|
63 | invalid = true;
|
---|
64 | }
|
---|
65 | m = null;
|
---|
66 | }
|
---|
67 | }
|
---|