java试用(3)awt,UI

程序 (注意要点: control, layout, 事件处理)

ExpandedBlockStart.gif 代码
import  java.awt. * ;
import  java.awt.event. * ;

public   class  MyFrame  extends  Frame{

    
private  TextField tf;

    
public   static   void  main(String args[ ]){
        MyFrame fr 
=   new  MyFrame( " Hello Out There! " );
        fr.InitUI();
    }

    
public  MyFrame (String str){
        
super (str);  // 调用父类的构造方法
    }

    
public   void  InitUI()
    {
        
// Frame
        
// setSize(200,200);
        setBackground(Color.red);
        

        
// setLayout(null);
        
// setLayout(new FlowLayout());
        
// setLayout(new BorderLayout());         // BAD
        setLayout( new  GridLayout( 2 , 3 ));        
        
// setLayout(new CardLayout());      // crash
        
// setLayout(new GridBagLayout());

        
// menus
        MenuBar mb  =   new  MenuBar();

        Menu m1 
=   new  Menu( " File " );
        Menu m2 
=   new  Menu( " Edit " );
        Menu m3 
=   new  Menu( " Help " );
        mb.add(m1);
        mb.add(m2);
        mb.setHelpMenu(m3);

        setMenuBar(mb);

        
//  controls
        Panel pan = new  Panel();
        pan.setSize(
100 , 100 );
        pan.setBackground(Color.yellow);

        Button b1 
=   new  Button( " Button1 " );
        b1.addActionListener(
new  ButtonHandler());

        Button b2 
=   new  Button( " Button2 " );
        b2.addActionListener(
new  ActionListener(){
                
public   void  actionPerformed(ActionEvent e)
                {
                    System.out.println(
" Action 2 occurred " );
                    tf.setText(
" Action 2 occurred " );
                }
            });
        
        tf
= new  TextField( 30 );

        
//  frames
        add(pan);
        add(b1);
        add(b2);
        add(tf);

        pack();

        addMouseMotionListener(
new  MouseMotionAdapter(){  // 匿名类开始
             public   void  mouseDragged(MouseEvent e){
                String s
= " Mouse dragging: x= " + e.getX() + " Y= " + e.getY();
                tf.setText(s); }
        } ); 
// 匿名类结束

        setVisible(
true );
    }
}

class  ButtonHandler  implements  ActionListener {
    
// 实现接口ActionListener才能做事件ActionEvent的处理者
     public   void  actionPerformed(ActionEvent e)
    
// 系统产生的ActionEvent事件对象被当作参数传递给该方法
    {
        System.out.println(
" Action occurred " );
    
// 本接口只有一个方法,因此事件发生时,系统会自动调用本方法,需要做的操作就把代码写在则个方法里。
    }
}


编译运行

 javac MyFrame.java

java MyFrame

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值