import jregex.*; import java.awt.*; import java.applet.*; import java.awt.event.*; public class Constrained extends Applet{ Label lText=new Label("Enter a text:"); Label lPatt=new Label("Enter a pattern:"); ConstrainedTextField textInput=new ConstrainedTextField(20); TextField patternInput=new TextField(20); public void init(){ setLayout(new GridLayout(2,2)); add(lText); add(lPatt); add(textInput); add(patternInput); patternInput.addTextListener(new TextListener(){ public void textValueChanged(TextEvent e){ setPattern(patternInput.getText()); } }); } public void start(){ patternInput.setText(getParameter("pattern")); } public void setPattern(String pattern){ try{ textInput.setPattern(new Pattern(pattern)); textInput.setEnabled(true); } catch(PatternSyntaxException e){ textInput.setEnabled(false); } } } class ConstrainedTextField extends TextField implements TextListener{ private String lastAccepted; private Matcher matcher; public ConstrainedTextField(int columns){ super(columns); addTextListener(this); } public void setPattern(Pattern p){ matcher=p.matcher(); lastAccepted=null; applyConstraint(); } public void textValueChanged(TextEvent e){ if(matcher==null) return; //no constraints applyConstraint(); } private void applyConstraint(){ String newValue=getText(); matcher.setTarget(newValue); if(matcher.matchesPrefix()){ //accept! lastAccepted=newValue; } else{ //reject getToolkit().beep(); removeTextListener(this); //avoid looping int cp=getCaretPosition(); setText(lastAccepted); setCaretPosition(cp); addTextListener(this); } } }