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

📄 keypress.java

📁 《JAVA程序设计教程》源代码
💻 JAVA
字号:
//KeyPress.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class KeyPress
{
	public static void main(String[] args)
	{  
		KeyFrame frame = new KeyFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.show();
	}
}

class KeyFrame extends JFrame
{
	public KeyFrame()
	{
		setTitle("KeyPress");
		setSize(WIDTH, HEIGHT);
		
		// 将panel加入到frame
		KeyPanel panel = new KeyPanel();
		Container contentPane = getContentPane();
		contentPane.add(panel);
	}
	
	public static final int WIDTH = 300;
	public static final int HEIGHT = 200;  	
}

class KeyPanel extends JPanel
	implements KeyListener
{  
	public KeyPanel()
	{  
		//注册监听器
		addKeyListener(this);
	}

	public boolean isFocusTraversable()
	{  
		//允许面板获得焦点
		return true; 
	}
		
	public void paintComponent(Graphics g)
	{  
		super.paintComponent(g);

		//输出虚拟键码
		if(KeyVirtualCode == -1)
			g.drawString("虚拟键码:", 100, 80);
		else
			g.drawString("虚拟键码:" + KeyVirtualCode, 100, 80);

		//输出键的名称
		g.drawString("键名称:"+ KeyText, 100, 110);

		//输出字符
		g.drawString("字符:"+ KeyChar, 100, 140);
	}
	
	public void keyPressed(KeyEvent event)
	{  
		//得到虚拟键码
		KeyVirtualCode = event.getKeyCode();
	}
	
	public void keyReleased(KeyEvent event)
	{  
		KeyVirtualCode = event.getKeyCode();

		//得到键的名称
		KeyText = event.getKeyText(KeyVirtualCode);
		
		//得到字符
		if(!isChar)
		{
			KeyChar= ' ';
		}
		isChar = false;

		repaint();
	}
	
	public void keyTyped(KeyEvent event)
	{  
		KeyChar = event.getKeyChar();
		isChar = true;
	}
	
	public char KeyChar = ' ';
	public int KeyVirtualCode = -1;
	public String KeyText = "";
	public boolean isChar = false;
}

⌨️ 快捷键说明

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