关于“<em>我可以在没有可视组件的情况下使用接口 KeyListener 吗?”</p>
是的,您可以(如果问题本身是问的):
package igb.so.SO19706590;
import static java.lang.System.out;
import java.awt.TextField;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
class KeyEventProducerConsumerSample {
public static void main( final String[] args ) {
final KeyEventProducerConsumerSample kes = new KeyEventProducerConsumerSample();
final KeyEventProducer kep = kes.new KeyEventProducer();
final KeyEventConsumer kec = kes.new KeyEventConsumer();
kep.addKeyListener( kec ).raise();
} // main()
class KeyEventProducer {
KeyListener kl;
KeyEventProducer addKeyListener( final KeyListener kl ) {
this.kl = kl;
return this;
} // addKeyListener()
/** Creating KeyEvents programmatically, with no keyboard involved
* and informing the KeyEventConsumer (KeyListener) about them.
*/
void raise() {
kl.keyTyped( new KeyEvent( new TextField(), 1, 1, 1, 1, '1' ) );
kl.keyPressed( new KeyEvent( new TextField(), 2, 2, 2, 2, '2' ) );
kl.keyReleased( new KeyEvent( new TextField(), 3, 3, 3, 3, '3' ) );
} // raise()
} // KeyEventProducer
/** Using KeyListener interface without any visual component.
*/
class KeyEventConsumer implements KeyListener {
@Override
public void keyTyped( final KeyEvent ke ) {
out.println( ke );
}
@Override
public void keyPressed( final KeyEvent ke ) {
out.println( ke );
}
@Override
public void keyReleased( final KeyEvent ke ) {
out.println( ke );
}
} // KeyEventConsumer
} // KeyEventProducerConsumerSample
输出
java.awt.event.KeyEvent[unknown type,keyCode=1,keyText=Unknown keyCode: 0x1,keyChar='1',modifiers=Shift,extModifiers=Shift,keyLocation=KEY_LOCATION_UNKNOWN,rawCode=0,primaryLevelUnicode=0,scancode=0,extendedKeyCode=0x0] on textfield0
java.awt.event.KeyEvent[unknown type,keyCode=2,keyText=Unknown keyCode: 0x2,keyChar='2',modifiers=Ctrl,extModifiers=Ctrl,keyLocation=KEY_LOCATION_UNKNOWN,rawCode=0,primaryLevelUnicode=0,scancode=0,extendedKeyCode=0x0] on textfield1
java.awt.event.KeyEvent[unknown type,keyCode=3,keyText=Cancel,keyChar='3',modifiers=Ctrl+Shift,extModifiers=Ctrl+Shift,keyLocation=KEY_LOCATION_UNKNOWN,rawCode=0,primaryLevelUnicode=0,scancode=0,extendedKeyCode=0x0] on textfield2