import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DemoLostFocus extends JApplet {
JTextField tf1, tf2;
JLabel label;
public void init() {
getContentPane().setLayout(new FlowLayout());
//
label = new JLabel("must be 'a' or 'b' ");
tf1 = new JTextField(5);
getContentPane().add(label);
getContentPane().add(tf1);
tf2 = new JTextField(5);
getContentPane().add(tf2);
tf1.addFocusListener(
new FocusListener() {
public void focusGained(FocusEvent e) {};
public void focusLost(FocusEvent e) {
if (!e.isTemporary() && isEnabled() ) {
String content = tf1.getText();
if (!content.equals("a") && !content.equals("b")) {
Toolkit.getDefaultToolkit().beep();
System.out.println("illegal value! " + content );
SwingUtilities.invokeLater(new FocusGrabber(tf1));
}
}}
});
}
}
class FocusGrabber implements Runnable {
private JComponent component;
public FocusGrabber(JComponent component) {
this.component = component;
}
public void run() {
component.grabFocus();
}
}
JDK1.3 provides a new class, InputVerfier, which can be used to do that.
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
// the first JTextField expects the string "howto" as input,
// and will allow focus to change only if the required string
// is typed.
class VerifierTest extends JFrame {
public VerifierTest () {
JTextField tf,tf2;
tf = new JTextField ("howto is required");
getContentPane().add (tf, BorderLayout.NORTH);
tf.setInputVerifier(new HowtoVerifier());
tf2 = new JTextField ("howto come here");
getContentPane().add (tf2, BorderLayout.SOUTH);
addWindowListener(new WindowCloser());
}
public static void main (String [] args) {
Frame f = new VerifierTest ();
f.pack();
f.show();
}
}
class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Window win = e.getWindow();
win.setVisible(false);
System.exit(0);
}
}
class HowtoVerifier extends InputVerifier {
public boolean verify(JComponent input) {
JTextField tf = (JTextField) input;
String pass = tf.getText();
return pass.equals("howto");
}
}
import javax.swing.border.*;
...
class HowtoVerifier extends InputVerifier {
public boolean verify(final JComponent input) {
JTextField tf = (JTextField) input;
String pass = tf.getText();
if (!pass.equals("howto")) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
input.setBorder( new LineBorder(Color.RED) );
}
});
return false;
}
SwingUtilities.invokeLater(new Runnable(){
public void run(){
input.setBorder( LineBorder.createBlackLineBorder() );
}
});
return true;
}
}
...
Written and compiled by Réal Gagnon ©1998-2007
[ home ]