JTextField 键盘监听事件 20

编了一段代码txtTransNumber是我的JTextField,TransNumber是我想要在JTextField上显示的值但是我每次在输入a~z的时候第一次总是会... 编了一段代码 txtTransNumber是我的JTextField,TransNumber是我想要在JTextField上显示的值 但是我每次在输入a~z的时候第一次总是会有字符出现后面就不出现还有删除时也是第一下删掉两个值,请问该怎么解决主要是不要显示出字符。
txtTransNumber.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event) {
if (event.getKeyCode() > KeyEvent.VK_9
| event.getKeyCode() < KeyEvent.VK_0) {
switch (event.getKeyCode()) {
case KeyEvent.VK_BACK_SPACE:
{
TransNumber = TransNumber.substring(0, TransNumber.length() - 1);
FrmTransNumber.this.txtTransNumber.setText(TransNumber);
}
break;
case KeyEvent.VK_ESCAPE: {
TransNumber = "";
FrmTransNumber.this.setVisible(false);
break;
}
case KeyEvent.VK_ENTER: {
TransNumber = FrmTransNumber.this.txtTransNumber.getText();
FrmTransNumber.this.setVisible(false);
break;
}
default: {
FrmTransNumber.this.txtTransNumber.setText(TransNumber);
TransNumber = TransNumber;
}
}
} else {
FrmTransNumber.this.txtTransNumber.setText(TransNumber);
TransNumber = TransNumber+ (char) event.getKeyCode();
}
}
});
展开
 我来答
lmy_sk521
2012-07-30 · TA获得超过2272个赞
知道小有建树答主
回答量:1330
采纳率:73%
帮助的人:728万
展开全部
public class FrmTransNumber extends JFrame implements KeyListener{

public JTextField txtTransNumber;
public String TransNumber;

public FrmTransNumber(){
txtTransNumber = new JTextField();
this.add(txtTransNumber,BorderLayout.NORTH);
this.addKeyListener(this);
this.setSize(300,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);

}

public static void main(String[] args) {
FrmTransNumber t = new FrmTransNumber();
}
@Override
public void keyPressed(KeyEvent event) {
if (event.getKeyCode() > KeyEvent.VK_9
| event.getKeyCode() < KeyEvent.VK_0) {
switch (event.getKeyCode()) {
case KeyEvent.VK_BACK_SPACE:
{
TransNumber = TransNumber.substring(0, TransNumber.length() - 1);
FrmTransNumber.this.txtTransNumber.setText(TransNumber);
}
break;
case KeyEvent.VK_ESCAPE: {
TransNumber = "";
FrmTransNumber.this.setVisible(false);
break;
}
case KeyEvent.VK_ENTER: {
TransNumber = FrmTransNumber.this.txtTransNumber.getText();
FrmTransNumber.this.setVisible(false);
break;
}
default: {
FrmTransNumber.this.txtTransNumber.setText(TransNumber);
TransNumber = TransNumber;
}
}
} else {
FrmTransNumber.this.txtTransNumber.setText(TransNumber);
TransNumber = TransNumber+ (char) event.getKeyCode();
}

}
public void keyReleased(KeyEvent e) {

}
public void keyTyped(KeyEvent e) {

}
}
是不是想要这样的效果
追问

输入字符后还是会在屏幕上显示啊。

已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式