import javax.swing.*; import java.awt.event.*; public class TestTextField implements KeyListener { JFrame f=new JFrame("Only can type 0 or 1"); JPanel p=new JPanel(); JLabel l=new JLabel("You only can type 0 or 1 in the textfield."); JTextField tf=new JTextField(10); public TestTextField() { f.getContentPane().add(p); p.add(l); p.add(tf); tf.addKeyListener(this); f.setSize(300,150); f.show(); } public void keyPressed(KeyEvent e) { }
import java.awt.event.*;
public class TestTextField implements KeyListener
{
JFrame f=new JFrame("Only can type 0 or 1");
JPanel p=new JPanel();
JLabel l=new JLabel("You only can type 0 or 1 in the textfield.");
JTextField tf=new JTextField(10);
public TestTextField()
{
f.getContentPane().add(p);
p.add(l);
p.add(tf);
tf.addKeyListener(this);
f.setSize(300,150);
f.show();
}
public void keyPressed(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
if(e.getSource()==tf)
{
if(!(tf.getText()).equals("0")&&!(tf.getText()).equals("1"))
{
System.out.println(tf.getText());
tf.setText("");
}
}
}
public void keyTyped(KeyEvent e)
{
}
public static void main(String args[])
{
new TestTextField();
}
}
粗略就是这样了,不知是否合乎你的要求?
不是贵族程序员,这个功能偶自己绝对能做出来的。但想了几种方案都觉得别扭,所以想向大家学习学习。优雅不过是个表达意思的词而已,如果您觉得调子太高,那偶也没办法了,偶就是喜欢这样说。:(
不过你的方案能解决从粘帖版拷贝不合法数据的问题吗?
不过还是觉得InputVerifier好,比较专业嘛
{
char ch=e.getKeyChar();
if(!(ch=='0'||ch=='1')){
e.consume();
}
}我不知道这样能否达到要求,我试过,好象也不能阻止输入其他的数据,只是可以对其他数据不做反应!