我希望我的程序能够监听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);
}
}
答案 0 :(得分:3)