try
{
   Double.parse...
}
catch (Exception e)
{
   //非数字字符。
}
如果要JTextArea只可键入数字,加多一个keylistener每次键入作判断。

解决方案 »

  1.   

    可以捕捉KeyEvent ke 事件,当输入的不是数字的时候,调用ke.consume()
    import java.awt.*;
    import java.awt.event.*;class KeyFilter {
      public static void main(String[] args) {
         final TextField tf = new TextField(20);
         
         tf.addKeyListener(new KeyAdapter() {
           public void keyTyped(KeyEvent ke) {
            
             if ((ke.getKeyChar()<0x30)||(ke.getKeyChar()>0x39)) 
                ke.consume();
              
            }
          });
          Frame f = new Frame();
          f.addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent we) {
                System.exit(0);
             }
         });
          
          f.add(tf);
          f.pack();
          f.setVisible(true);
          f.show();
      }
    }
      

  2.   

    这种方法也可以实现,但是我觉得darkway(黑道) 的方法更加简单,方便。public class JTextArea_DocumentIntOnly extends JFrame {
        JTextField tf = new JTextField(30);    public JTextArea_DocumentIntOnly() {
            Container contentPane = getContentPane();
            JLabel label = new JLabel("Enter an Integer:");
            
            //tf.setDocument(new IntegerDocument());
            tf.setDocument(new DateDocument(this.tf));
            
            contentPane.setLayout(new FlowLayout()); 
            contentPane.add(label);
            contentPane.add(tf);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
        }
        public static void main(String[] args) {
            JTextArea_DocumentIntOnly JTextArea_DocumentIntOnly1 = new JTextArea_DocumentIntOnly();
            JTextArea_DocumentIntOnly1.pack() ;
            JTextArea_DocumentIntOnly1.show() ;
        }
    }class IntegerDocument extends PlainDocument {
        public void insertString(int offset, String s, AttributeSet attributeSet)throws BadLocationException {
            try {
                Integer.parseInt(s);
                super.insertString(offset, s, attributeSet);
            }
            catch(Exception ex) { // only allow integer values
                Toolkit.getDefaultToolkit().beep();
                System.out.println("Integer Only!");
                return; 
            }        
        }
    }