text.addDocumentListener(new MyDocumentListener());
protected class MyDocumentListener implements DocumentListener {
    public void insertUpdate(DocumentEvent e) {
        displayEditInfo(e);
    }
    public void removeUpdate(DocumentEvent e) {
        displayEditInfo(e);
    }
    public void changedUpdate(DocumentEvent e) {
        displayEditInfo(e);
    }
    private void displayEditInfo(DocumentEvent e) {//判断和显示字符    }

解决方案 »

  1.   

    给你一个例子:以后开贴加分
    public class ValidationTest {
      public static void main(String[] args)
      {
      ValidationTestFrame frame=new ValidationTestFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.show();
      }}class ValidationTestFrame extends JFrame
    {
      public ValidationTestFrame()
      {
        setTitle("有效性测试");
        setSize(300,300);
        Toolkit kit=Toolkit.getDefaultToolkit();
        Dimension screenSize=kit.getScreenSize();
        int width=screenSize.width;
        int height=screenSize.height;
        setLocation((width-300)/2,(height-300)/2);    Container contentPane=getContentPane();
        JPanel panel=new JPanel();    hourField=new IntTextField(12,3);
        panel.add(hourField);
        minuteField=new IntTextField(0,3);
        panel.add(minuteField);    JButton setButton=new JButton("set");
        panel.add(setButton);
        setButton.addActionListener(new ActionListener()
                                    {
                                      public void actionPerformed(ActionEvent event)
                                          {
                                            if(hourField.isValid(1) && minuteField.isValid(2))
                                              clock.setTime(hourField.getValue(),minuteField.getValue());
                                          }
                                    });
        contentPane.add(panel,BorderLayout.SOUTH);    clock=new ClockPanel();
        contentPane.add(clock,BorderLayout.CENTER);
      }
      private IntTextField hourField,minuteField;
      private ClockPanel clock;
    }class IntTextDocument extends PlainDocument
    {
      public void insertString(int offs,String str,AttributeSet a)
          throws BadLocationException
      {
        if(str==null) return ;
        String oldString=getText(0,getLength());
        String newString=oldString.substring(0,offs)+str+oldString.substring(offs);
        if(canBecomeValid(newString))
          super.insertString(offs,str,a);
      }  public static boolean isValid(String s)
      {
        try
        {
          Integer.parseInt(s);
          return true;
        }
        catch(NumberFormatException e)
        {
          return false;
        }
      }  public static boolean canBecomeValid(String s)
      {
        return s.equals("")||s.equals("-")||isValid(s);
      }
    }class IntTextField extends JTextField
    {
      public IntTextField(int defval,int size)
      {
        super(""+defval,size);
        setInputVerifier(new IntTextFieldVerifier());  }  protected Document createDefaultModel()
      {
        return new IntTextDocument();
      }  public boolean isValid(int i)
      {
        if(i==1)
        return IntTextDocument.isValid(getText());
        else
        return IntTextDocument.isValid(getText());
      }  public int getValue()
      {
        try
        {
          return Integer.parseInt(getText());
        }
        catch(NumberFormatException e)
        {
          return 0;
        }
      }
    }class IntTextFieldVerifier extends InputVerifier
    {
      public boolean verify(JComponent component)
      {
        String text=((JTextComponent)component).getText();
        return IntTextDocument.isValid(text);
      }
    }class ClockPanel extends JPanel
    {
      public void paintComponent(Graphics g)
      {
        super.paintComponent(g);
        Graphics2D g2=(Graphics2D)g;
        Ellipse2D circle=new Ellipse2D.Double(0,0,200,200);
        g2.draw(circle);    double hourAngle=Math.toRadians(90-360*minutes/720);
        drawHand(g2,hourAngle,60);    double minuteAngle=Math.toRadians(90-360*minutes/60);
        drawHand(g2,minuteAngle,80);
      }  public void drawHand(Graphics2D g2,double angle,double handlength)
      {
        Point2D end=new Point2D.Double(100+handlength*Math.cos(angle),100-handlength*Math.sin(angle));
        Point2D center=new Point2D.Double(100,100);
        g2.draw(new Line2D.Double(center,end));
      }  public void setTime(int h,int m)
      {
        minutes=h*60+m;
        repaint();
      }
      private double minutes=0;
    }
      

  2.   

    qiyongjun2003(风也悄悄)
    能不能不用 javax 包??
      

  3.   

    给思路你吧:)
    1。frame中加入TextArea
    2。TextArea叫KeyListener(new KeyAdapter())
    3。在KeyAdapter中的keyTyped()方法中判断KeyEvent的值是否为0~9,不是给出提示,并清空TextArea。
    思路应该没错的,具体的可以查阅doc:)
      

  4.   

    这是doc中的例子,我改了一下,可以扩充到对整个frame中所有TextField进行任何判断了
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Vertify extends JFrame {
    PassVerifier p = new PassVerifier();
    public JTextField tf1 = new JTextField ("Type \"pass\" here");
    public JTextField tf2 = new JTextField ("TextField2");
         public Vertify() {
    tf1 = new JTextField ("Type \"pass\" here");
         getContentPane().add (tf1, BorderLayout.NORTH);tf2 = new JTextField ("TextField2");
         getContentPane().add (tf2, BorderLayout.SOUTH);
    tf2.setInputVerifier(p);
         tf1.setInputVerifier(p);
    JTextField tf3 = new JTextField ("TextField3");
         getContentPane().add (tf3, BorderLayout.CENTER);
         WindowListener l = new WindowAdapter() {
             public void windowClosing(WindowEvent e) { 
                 System.exit(0); 
             }
         };
         addWindowListener(l);
         }
     
         public class PassVerifier extends InputVerifier {
        
             public boolean verify(JComponent input) {
             JTextField tf = (JTextField) input;
                   if(tf.equals(tf1))
                   {
              return "pass".equals(tf.getText());
                   }
                   if(tf.equals(tf2))
                   {
              return "ok".equals(tf.getText());
                   }
                   else
    {
    return false;
    }
             }
         }
     
         public static void main(String[] args) {
             Frame f = new Vertify();
         f.pack();
         f.setVisible(true);
         }
     }
      

  5.   

    我还是直接说了吧
    我是用 Visual J++ 编程,它不支持 javax.swing 组件,
    所以想问大家如何用键盘事件处理 TextField 只允许输入数字的问题
    主要的 bug 是按下一个非数字键时文本框会显示一下该字符然后把它删掉
    谁能帮帮我啊??
      

  6.   

    总之,要做出像 QQ 用户名输入文本框(TextField 类)效果 就马上给分
      

  7.   

    既然是不能用swing的话,用这个思路是没问题的啊。1。frame中加入TextArea
    2。TextArea加KeyListener(new KeyAdapter())
    3。在KeyAdapter中的keyTyped()方法中判断KeyEvent的值是否为0~9,不是给出提示,并清空TextArea。你试过没有?
      

  8.   

    当然试过
    我要的效果是如果按下的键不是数字,则不予处理,也就是不在TextField中加入该字符,
    而不是清空文本框,这样做的问题就是按下一个非数字键时文本框会显示一下该字符然后把它删掉,就是这个问题.......
    能不能解决??
      

  9.   

    JAVA核心技术I中的事件处理一单元中有,可以用销毁事件,也可以用输入确认!
      

  10.   

    用我这个监听器类吧,应该是没问题的!
    class keyevent extends KeyAdapter      // 文本框验证类(验证文本框输入的是否是数字和“-”)
    {
    int k;
    keyevent(int ik)
    {
    k = ik;
    }
    public void keyReleased(KeyEvent e)
    {
    if(e.getKeyCode()!=KeyEvent.VK_BACK_SPACE
    && e.getKeyChar()!='0' 
    && e.getKeyChar()!='1' && e.getKeyChar()!='2'
    && e.getKeyChar()!='3' && e.getKeyChar()!='4'
    && e.getKeyChar()!='5' && e.getKeyChar()!='6'
    && e.getKeyChar()!='7' && e.getKeyChar()!='8'
    && e.getKeyChar()!='9' )
    {
    if(k==1)
    {
    if(stime.getText().equals("")!=true)
    stime.setText(stime.getText().substring(0,(stime.getText().length()-1)));
    else
    stime.setText("");
    }
    if(k==2)
    {
    if(etime.getText().equals("")!=true)
    etime.setText(etime.getText().substring(0,(etime.getText().length()-1)));
    else
    etime.setText("");
    }
    }
    }
    }
    监听器会用吧,别告诉我你不会添加我这个类呢!
      

  11.   

    noratong(诺拉) 
    你自己试试,做出像 QQ 用户名输入文本框(TextField 类)效果了吗?
    我说的 bug 依然存在!!
      

  12.   

    通过键盘事件,取得ASCII码,来限制数字的输入
      

  13.   

    可以用event.consume()jTextField1.addKeyListener(new KeyAdapter()
                               {
                                public void keyTyped(KeyEvent event)
                                {
                                  char ch=event.getKeyChar();
                                  if(ch < '0' || ch > '9')
                                    event.consume();                            }
                                }
                                 );更复杂的,比如复制过来的情况可以参考core java I的文本输入-输入确认