⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 keyeventdemo.java

📁 Java面向对象编程(随书配套源代码) 阐述了面向对象编程的思想
💻 JAVA
字号:
package chapter14;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyEventDemo implements ActionListener,KeyListener
{
    JFrame frmMain;
    JLabel lblInfo,lblTest,lblEvent;
    JTextField txtTest,txtInfo;
    JButton btnClear=null;
    String strKey="";
    public KeyEventDemo()
    {
       frmMain=new JFrame("键盘事件演示");
       Container conPane=frmMain.getContentPane();
       conPane.setLayout(new GridLayout(3,2));
       lblInfo=new JLabel("您的输入:");
       txtInfo=new JTextField();
       txtInfo.setBackground(Color.CYAN);
       txtInfo.enable(false);
       lblTest=new JLabel("输入字符:");
       txtTest=new JTextField();
       txtTest.requestFocus();
       txtTest.addKeyListener(this);
       lblEvent=new JLabel();
       btnClear=new JButton("重置(C)");
       btnClear.setMnemonic('C');
       btnClear.addActionListener(this);
       Font fntDisp=new Font("宋体",Font.PLAIN,12);
       lblTest.setFont(fntDisp);
       txtTest.setFont(fntDisp);
       lblInfo.setFont(fntDisp);
       txtInfo.setFont(fntDisp);
       lblEvent.setFont(fntDisp);
       btnClear.setFont(fntDisp);
       conPane.add(lblTest);
       conPane.add(txtTest);
       conPane.add(lblInfo);
       conPane.add(txtInfo);
       conPane.add(lblEvent);
       conPane.add(btnClear);
       frmMain.setSize(250,150);
       frmMain.show();
    }
    public void actionPerformed(ActionEvent e)
    {
       strKey="";
       txtInfo.setText("");
       txtTest.setText("");
       txtTest.requestFocus();       
    }
    public void keyTyped(KeyEvent e)
    {
       char c=e.getKeyChar();/*注意getKeyChar()的用法*/
       strKey=strKey+c;
       txtInfo.setText(strKey);
       lblEvent.setText("产生keyTyped!");
    }
    public void keyPressed(KeyEvent e)
    {
    	lblEvent.setText("产生keyPressed!");
    }
    public void keyReleased(KeyEvent e)
    {
    	lblEvent.setText("产生keyReleased!");	
    }

    public static void main(String[] args)
    {
        new KeyEventDemo(); 
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -