怎样获得键盘事件
怎样在面板中获得键盘事件import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class D extends JFrame
{
public D()
{
setSize(300,200);
setVisible(true);
this.getContentPane().add(new AA());
}
public static void main(String args[])
{
new D();
}
}
class AA extends JPanel
{
JTextField text1;
JTextField text2;
JButton button1;
JButton button2;
public AA()
{
text1=new JTextField(15);
text2=new JTextField(15);
button1=new JButton("确定");
button2=new JButton("取消");
this.setLayout(new FlowLayout());
add(text1);
add(text2);
add(button1);
add(button2);
this.requestFocus();
System.out.println("aaaaaaaaa");
this.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==e.VK_ENTER)
System.out.println("aaaaaaaaa");
}
});
}
}
搜索更多相关的解决方案:
键盘
----------------解决方案--------------------------------------------------------
this.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==e.VK_ENTER)
System.out.println("aaaaaaaaa");
}
这句已实现键盘监听功能,但你没有实现keyListener接口.在public class D extends JFrame后加上这句:implements KeyListener
----------------解决方案--------------------------------------------------------
天一, code for you, usually we don't need KeyListener for JPanel import java.awt.event.*; import javax.swing.*; class AA extends JPanel { JTextField text1; JTextField text2; JButton button1; JButton button2; public AA() { text1=new JTextField(15); text2=new JTextField(15); button1=new JButton("确定"); button2=new JButton("取消"); //setLayout(new FlowLayout()); //here FlowLayout is not necessary, //because by daufault the LayoutManager is already FlowLayout add(text1); add(text2); add(button1); add(button2); System.out.println("aaaaaaaaa"); } } public class Frame1 extends JFrame { public Frame1() { super("Test"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); AA aa = new AA(); // to make sure the JPanel aa is focused aa.setFocusable(true); aa.addKeyListener(new MyKeyListener()); setContentPane(aa); } public static void main(String args[]) { Frame1 frame1 = new Frame1(); frame1.pack(); frame1.setVisible(true); } class MyKeyListener implements KeyListener { public void keyPressed(KeyEvent e) { if(e.getKeyCode() == e.VK_ENTER) System.out.println("Enter Pressed"); } public void keyReleased(KeyEvent e) { System.out.println("keyReleased"); } public void keyTyped(KeyEvent e) { System.out.println("keyTyped"); } } }
----------------解决方案--------------------------------------------------------
谢谢你,我的问题解决了
----------------解决方案--------------------------------------------------------