importjava.awt.*;importjava.awt.event.*;publicclassMyFrameextendsFrame{privateTextField tf;publicstaticvoidmain(String args[ ]){
MyFrame fr=newMyFrame("Hello Out There!");
fr.InitUI();
}publicMyFrame (String str){super(str);//调用父类的构造方法}publicvoidInitUI()
{//Frame//setSize(200,200);setBackground(Color.red);//setLayout(null);//setLayout(new FlowLayout());//setLayout(new BorderLayout());//BADsetLayout(newGridLayout(2,3));//setLayout(new CardLayout());//crash//setLayout(new GridBagLayout());//menusMenuBar mb=newMenuBar();
Menu m1=newMenu("File");
Menu m2=newMenu("Edit");
Menu m3=newMenu("Help");
mb.add(m1);
mb.add(m2);
mb.setHelpMenu(m3);
setMenuBar(mb);//controlsPanel pan=newPanel();
pan.setSize(100,100);
pan.setBackground(Color.yellow);
Button b1=newButton("Button1");
b1.addActionListener(newButtonHandler());
Button b2=newButton("Button2");
b2.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvent e)
{
System.out.println("Action 2 occurred");
tf.setText("Action 2 occurred");
}
});
tf=newTextField(30);//framesadd(pan);
add(b1);
add(b2);
add(tf);
pack();
addMouseMotionListener(newMouseMotionAdapter(){//匿名类开始publicvoidmouseDragged(MouseEvent e){
String s="Mouse dragging: x="+e.getX()+"Y="+e.getY();
tf.setText(s); }
} );//匿名类结束setVisible(true);
}
}classButtonHandlerimplementsActionListener {//实现接口ActionListener才能做事件ActionEvent的处理者publicvoidactionPerformed(ActionEvent e)//系统产生的ActionEvent事件对象被当作参数传递给该方法{
System.out.println("Action occurred");//本接口只有一个方法,因此事件发生时,系统会自动调用本方法,需要做的操作就把代码写在则个方法里。}
}