importjava.awt.BorderLayout;importjava.awt.Button;importjava.awt.Frame;importjava.awt.Label;importjava.awt.TextField;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.MouseEvent;importjava.awt.event.MouseListener;importjava.awt.event.MouseMotionListener;importjava.awt.event.WindowEvent;importjava.awt.event.WindowListener;importjava.sql.Date;public class MyWindow implementsMouseListener, MouseMotionListener
{privateFrame frame;privateLabel label;privateButton button;privateTextField textField;public voidgo()
{
frame= new Frame("My Frame");//加上窗口监听器,其中主要实现了退出功能
frame.addWindowListener(newMyWindowListener());//加一个标签
label = new Label("This is my Window");
frame.add(label, BorderLayout.NORTH);//加一个按钮
button = new Button("MyButton");
frame.add(button, BorderLayout.WEST);//设置按钮事件监听器,按钮按下时会向控制台输出信息
button.addActionListener(newMyButtonListener());//加一个文本编辑框
textField = new TextField(40);
frame.add(textField, BorderLayout.SOUTH);//加上鼠标动作监听器,因为类本身实现了这两个接口,所以参数是this
frame.addMouseListener(this);
frame.addMouseMotionListener(this);//可以添加多个监听器,所以还可以定义其他的,如MyMouseListener类,然后加上//设置刚好能容纳这些控件的尺寸
frame.pack();//设置为可见
frame.setVisible(true);
}public static voidmain(String[] args)
{
MyWindow window= newMyWindow();
window.go();
}
@Overridepublic voidmouseDragged(MouseEvent e)
{
}
@Overridepublic voidmouseMoved(MouseEvent e)
{
String str= "x = " + e.getX() + ", y = " +e.getY();this.textField.setText(str);
System.out.println(str);
}
@Overridepublic voidmouseClicked(MouseEvent e)
{
}
@Overridepublic voidmouseEntered(MouseEvent e)
{
}
@Overridepublic voidmouseExited(MouseEvent e)
{this.textField.setText("the mouse has exited.");
}
@Overridepublic voidmousePressed(MouseEvent e)
{
}
@Overridepublic voidmouseReleased(MouseEvent e)
{
}
}class MyButtonListener implementsActionListener
{
@SuppressWarnings("deprecation")
@Overridepublic voidactionPerformed(ActionEvent e)
{//输出信息
System.out.println("The Button is pressed!");//输出时间戳
Long time =e.getWhen();
System.out.println("timestamp: " +time);//日期时间
Date date = newDate(time);
System.out.println(date.toLocaleString());
}
}class MyWindowListener implementsWindowListener
{
@Overridepublic voidwindowActivated(WindowEvent e)
{
}
@Overridepublic voidwindowClosed(WindowEvent e)
{
}
@Overridepublic voidwindowClosing(WindowEvent e)
{
System.out.println("windowClosing");//退出
System.exit(0);
}
@Overridepublic voidwindowDeactivated(WindowEvent e)
{
}
@Overridepublic voidwindowDeiconified(WindowEvent e)
{
}
@Overridepublic voidwindowIconified(WindowEvent e)
{
}
@Overridepublic voidwindowOpened(WindowEvent e)
{
}
}