阅读背景:

GUI编程 鼠标事件和键盘事件_hoho_12

来源:互联网 
import java.awt.*;
import java.awt.event.*;


class MouseAndKeyEvent 
{
	private Frame f;
	private Button but;
	private TextField tf;

	MouseAndKeyEvent()
	{
		init();
	}

	public void init()
	{
		f = new Frame("my frame");

		f.setBounds(300,100,600,500);
		f.setLayout(new FlowLayout());

		tf = new TextField(20);

		but = new Button("my button");
		
		f.add(tf);
		f.add(but);

		myEvent();

		f.setVisible(true);

	}
	private void myEvent()
	{
		f.addWindowListener(new WindowAdapter()
		{
			public void windowClosing(WindowEvent e)
			{
				System.exit(0);
			}
		});


		tf.addKeyListener(new KeyAdapter()
		{
			public void keyPressed(KeyEvent e)
			{
				int code = e.getKeyCode();
				if(!(code>=KeyEvent.VK_0 && code<=KeyEvent.VK_9))
				{
					System.out.println(code+".....是非法的");
					e.consume();//取消事件,不让非法字符出现在文本框
				}
			}
		});

		//给But添加一个键盘监听。
		but.addKeyListener(new KeyAdapter()
		{
			public void keyPressed(KeyEvent e)
			{	
				if(e.isControlDown()&&e.getKeyCode()==KeyEvent.VK_ENTER)
					//System.exit(0);
				System.out.println("ctrl+enter is run");

				//System.out.println(KeyEvent.getKeyText(e.getKeyCode

())+"...."+e.getKeyCode());
			}
		});

		/*
		//活动监听
		but.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				System.out.println("action ok");
			}
		});
		*/

		/*
		//鼠标监听

		but.addMouseListener(new MouseAdapter()
		{
			private int count = 1;
			private int clickCount = 1;
			public void mouseEntered(MouseEvent e) 
			{
				System.out.println("鼠标进入到该组件"+count++);
			}
			public void mouseClicked(MouseEvent e)
			{
				if(e.getClickCount()==2)
					System.out.println("双击动作"+clickCount++);
			}
		});
		*/
	}
	public static void main(String[] args) 
	{
		new MouseAndKeyEvent();
	}
}import java.awt.*;
import java.awt.event.*;


c



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: