import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TestKey extends JPanel{
private JTextField jtf;
private JTextArea jta;
TestKey(){
this.jtf=new JTextField(10);
this.jta=new JTextArea(10,10);
this.add(this.jtf);
this.add(this.jta);
getKey();
}
public void getKey(){
this.jtf.addKeyListener(new TestKeyListener(this));
}
public void setKey(){
this.jta.setText(this.jtf.getText());
}
}
class TestKeyListener implements KeyListener {
private TestKey tk;
TestKeyListener(TestKey tk){
this.tk=tk;
}
public void keyPressed(KeyEvent kevent){
tk.setKey();//想只有当回车键按下时才引发事件得怎么写?
}
public void keyReleased(KeyEvent kevent) {
}
public void keyTyped(KeyEvent kevent) {
}
}
class TestKeyDemo{
public static void main(String args[]){
JFrame frame=new JFrame( "处理键盘事件 ");
frame.setSize(180,300);
frame.add(new TestKey());
frame.setVisible(true);
}
}
//想只有当回车键按下时才引发事件得怎么写?
------解决方案--------------------
if(kevent.getKeyCode()==KeyEvent.VK_ENTER)
tk.setKey();
可以么