import
javax.swing.*;
import
java.awt.*;
import
java.awt.event.*;
public
class
FrameEvent
extends
JFrame
implements
KeyListener {
JTextArea textarea =
new
JTextArea(
10
,
30
);
private
JLabel status;
public
FrameEvent() {
super
(
"KeyinEvent.java: "
);
Container c = getContentPane();
c.setLayout(
new
FlowLayout());
setFocusable(
true
);
textarea.setText(
"请按任意键:"
);
c.add(textarea);
addKeyListener(
this
);
setSize(
350
,
300
);
show();
this
.setDefaultCloseOperation(
3
);
}
public
void
keyPressed(KeyEvent e) {
// String line1="按键:"+e.getKeyChar()+"\n";
// String line2="a按键是否为Action键:"+e.isActionKey();
// @SuppressWarnings("static-access")
// String mKey=e.getKeyModifiersText(e.getModifiers());
// String line3="是否按下Modifier键"+(mKey.equals("")?"否":"是,其键为"+mKey);
// textarea.setText(line1+"\n"+line2+"\n"+line3+"\n");
if
(e.getKeyCode() == KeyEvent.VK_SPACE) {
System.out.println(
"123"
);
}
// char ch = e.getKeyChar();
// status.setText(String.valueOf(ch) + " " +(int)ch);
}
public
void
keyReleased(KeyEvent e) {
}
public
void
keyTyped(KeyEvent e) {
}
public
static
void
main(String args[]) {
FrameEvent app =
new
FrameEvent();
}
}
|
追问:
您好,我看了一下你的代码,你可否告诉我为什么不加上setFocusable(true);这句,就不能触发事件呢?
追答:
这是swing的焦点问题,JFrame 、JComponent、JLabel默认是不可以获得焦点,而且默认情况下,swing是把焦点分配给容器内可以获得焦点的第一个组件