.......this.jTextField.addKeyListener(this);.......
public void keyPressed(KeyEvent e)
{
this.jTextField.setText("");
String sKeyPress = "";
if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE)
{
this.jTextField.setText("");
}
else
{
if(e.isAltDown())
{
sKeyPress = sKeyPress+"Alt+";
}
if(e.isControlDown())
{
sKeyPress = sKeyPress+"Clr+";
}
if(e.isShiftDown())
{
//sKeyPress = sKeyPress+"Sht+";
}
if(sKeyPress.split("\\+").length>3)
{
sKeyPress = "";
}
//System.out.println(e.getKeyCode());
sKeyPress = sKeyPress+e.getKeyChar();
this.jTextField.setText(sKeyPress);
}
}
现在我如果按Crl+任何一个键,jTextField中显示"Crl+",那个键获取到的KeyCode为0,但是按Alt+任意键又是正常的这是怎么回事?难道无法获取Crl+XX或者Crl+Alt+XX这种组合键事件么?QQ的热键方式不也是Swing做的,它怎么实现的?
public void keyPressed(KeyEvent e)
{
this.jTextField.setText("");
String sKeyPress = "";
if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE)
{
this.jTextField.setText("");
}
else
{
if(e.isAltDown())
{
sKeyPress = sKeyPress+"Alt+";
}
if(e.isControlDown())
{
sKeyPress = sKeyPress+"Clr+";
}
if(e.isShiftDown())
{
//sKeyPress = sKeyPress+"Sht+";
}
if(sKeyPress.split("\\+").length>3)
{
sKeyPress = "";
}
//System.out.println(e.getKeyCode());
sKeyPress = sKeyPress+e.getKeyChar();
this.jTextField.setText(sKeyPress);
}
}
现在我如果按Crl+任何一个键,jTextField中显示"Crl+",那个键获取到的KeyCode为0,但是按Alt+任意键又是正常的这是怎么回事?难道无法获取Crl+XX或者Crl+Alt+XX这种组合键事件么?QQ的热键方式不也是Swing做的,它怎么实现的?
改成sKeyPress = sKeyPress+e.getKeyCode();看看getKeyChar的api说明:public char getKeyChar()
Returns the character associated with the key in this event. For example, the KEY_TYPED event for shift + "a" returns the value for "A".
KEY_PRESSED and KEY_RELEASED events are not intended for reporting of character input. Therefore, the values returned by this method are guaranteed to be meaningful only for KEY_TYPED events.
Returns:
the Unicode character defined for this key event. If no valid Unicode character exists for this key event, CHAR_UNDEFINED is returned.
你说的方法我试过了的,在keyType事件中Crl+XX这种组合方式会被认做一个控制键,这时候用e.getKeyCode取得的值都是0,只能在keyPress事件中做处理。问题已解决,方法如下:
.......this.jTextField.addKeyListener(this);.......
public void keyPressed(KeyEvent e)
{
int iClrFlag = 0 ,iAltFlag = 0;
this.keyCodeString = "";
if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE)
{
this.jTextField.setText("");
}
else
{
if(e.isAltDown())
{
iAltFlag = 1;
}
if(e.isControlDown())
{
iClrFlag = 1;
}
if(e.isShiftDown())
{
}
}
if(iAltFlag == 1)
{
this.keyCodeString = this.keyCodeString + "Alt+";
}
if(iClrFlag == 1)
{
this.keyCodeString = this.keyCodeString + "Clr+";
}
if( (keyCodeString.indexOf("+")>0)&&(keyCodeString.split("\\+").length>3))
{
keyCodeString = "";
}
String sKeyCodeTmp = e.getKeyText(e.getKeyCode());
if( (sKeyCodeTmp.endsWith("Ctrl"))||(sKeyCodeTmp.endsWith("Alt")) )
{
this.jTextField.setText("");
}
else
{
this.keyCodeString = keyCodeString+sKeyCodeTmp;
this.jTextField.setText(this.keyCodeString);
}
}
可能做的复杂了些,但毕竟能够在文本框中跟踪用户的组合键事件了,呵呵。
应该有更好的办法,大家再看看,如果没有回帖了就结帖。