JAVA—GUI(图形用户界面)编程

import java.awt.*;
import java.awt.event.*;

class Demo
{
	private Frame f;
	private Button but;
	private TextField tf;
	static int i = 0;
	
	Demo()
	{
		init();
	}
	public void init()
	{
		f = new Frame("Demo");
		f.setBounds(300,100,600,500); //设置位置和大小,距离左边(y轴)300,距离上面(x轴)100;
										//长600,高500;
		f.setLayout(new FlowLayout());  
		
		tf = new TextField("我爱你",20);
		
		
		but = new Button("按钮");
		
		f.add(tf);
		f.add(but);
		
		f.setVisible(true);
		
		myEvent();    // 调用X关闭事件
		System.out.println("hahahahaahaha");
	}
	private void myEvent()
	{
		f.addWindowListener(new WindowAdapter() //使得能够按X能够关闭框框;
		{
			public void windowClosing(WindowEvent e)
			{
				//System.out.println(i); //用来记录按了几次按钮 
				System.exit(0);
			}
		});
	
	 
	but.addActionListener(new ActionListener()  //设置按钮点击事件
	{
		
		public void actionPerformed(ActionEvent e)
		{
			System.out.println("action on");
			i++;
		}
		
	});
	but.addMouseListener(new MouseAdapter()//鼠标点击事件 
	{
		private int count = 1,clickCount = 1;
		public void mouseEntered(MouseEvent e) // 鼠标进入 激发时间
		{
			System.out.println("mouse enter" + count++);
		}
		public void mouseClicked(MouseEvent e) //鼠标点击事件
		{
			if(e.getClickCount() == 2)
				System.out.println("mouse click" + clickCount++);
		}
	});
	
	tf.addKeyListener(new KeyAdapter() //键盘事件
	{
		public void keyPressed(KeyEvent e)
		{
			int code = e.getKeyCode();
			if(!(code>= KeyEvent.VK_0 && code<=KeyEvent.VK_9))// 设置只能输入数字,而且code代表单个输入的ascll码,
															//而KeyEvent.VK_0=48;KeyEvent.VK_9=57;
			{
				System.out.println(code + "……是非法的!");
				  e.consume(); //用来屏蔽键盘
			}
			if(e.getKeyCode() == KeyEvent.VK_ESCAPE) //实现按Esc为退出键;
				System.exit(0);
			if(e.isControlDown() && e.getKeyCode() == KeyEvent.VK_ENTER)//结合组合键Ctrl+Enter;
				System.out.println("Hello");
		}
	});
	
	/*
	but.addKeyListener(new KeyAdapter()
	{
		public void keyPressed(KeyEvent e)
		{
			if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
				System.exit(0);
			if(e.isControlDown() && e.getKeyCode() == KeyEvent.VK_ENTER)//结合组合键Ctrl+Enter;
				System.out.println("Hello");
		}
	});
	*/
	}
	public static void main(String[] args)
	{
		new Demo();
	}
}

你可能感兴趣的:(Java学习)