我无法在Java中为我的程序找到合适的监听器

时间:2013-12-29 00:26:00

标签: java listener

我希望我的程序能够监听textField,并且必须允许用户只键入数字字符。如果用户键入非数字字符,程序不应显示该字符。无论我做了什么,我都无法解决这个问题。你能帮我解决这个问题吗?这是我的代码

package textfieldlistener;

import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.BorderLayout;
import java.awt.GridLayout;
public class Components extends JFrame {

private JTextField comp1 = new JTextField(20);
private JTextField comp2 = new JTextField(20);
private JButton button1 = new JButton("Run");
private JButton button2 = new JButton("Delete");
private JPanel panel1 = new JPanel();
private StringBuffer input1 = new StringBuffer("");
private StringBuffer input2 = new StringBuffer("");
public Components()
{

    panel1.setLayout(new GridLayout(2,2,10,10));
    panel1.add(comp1);
    panel1.add(comp2);
    panel1.add(button1);
    panel1.add(button2);

    setLayout(new BorderLayout());
    add(panel1, BorderLayout.SOUTH);
    comp1.addKeyListener(new KeyAdapter() {


public void keyPressed(KeyEvent e) {

if(e.getKeyCode() == KeyEvent.VK_0 || e.getKeyCode() == KeyEvent.VK_3 ||
  e.getKeyCode() == KeyEvent.VK_1 || e.getKeyCode() == KeyEvent.VK_2 ||
  e.getKeyCode() == KeyEvent.VK_4 || e.getKeyCode() == KeyEvent.VK_5 ||
  e.getKeyCode() == KeyEvent.VK_6 || e.getKeyCode() == KeyEvent.VK_7 ||
  e.getKeyCode() == KeyEvent.VK_8 || e.getKeyCode() == KeyEvent.VK_9)
 {
  input1.append(KeyEvent.getKeyText(e.getKeyCode()));
  comp1.setText(input1.substring(0, input1.length()-1));

 }
else
 {
   if(input1.equals(""))
    {
      comp1.setText(""); 
     }
  else
  {

     comp1.setText(input1.substring(0, input1.length()));
  }
}


}
    });



}

public static void main(String[]args)
{
    Components app = new Components();
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    app.setSize(400, 300);
    app.setVisible(true);
}

}

1 个答案:

答案 0 :(得分:3)

最合适的方法可能是使用DocumentFilter

请参阅...

如果您认为这可能会很难,请尝试使用;

当字段失去焦点时,您还可以考虑使用Input Verifier来验证文字