黑马程序员_JAVA笔记22——GUI

-------  android培训java培训、期待与您交流! ----------

一、GUI  (图形用户界面)
        JAVA为GUI提供的对象都存在java.Awt和javax.Swing两个包中。
        java.Awt:Abstract Window ToolKit(抽象工具包),需要调用本地系统方法实现功能,属于重量级控件。(比较依赖于平台)
        javax.Swing:在AWT的基础上,建立一套图形界面系统,其中提供了更多的组件,而且完全有java实现,增强了移植性,属于轻量级控件(跨平台,在任何平台上都一样)
二、继承关系图
        container:为容器,是一个特殊的组件。该组件及其子类中可以通过add方法添加其他组件进来。(其他不能添加组件)
        Component:
                Container:
                        Window:
                                Frame:窗体
                                Dialog:对话框
                                        FileDialog:文件对话框
                        Panel:
                Button:
                Label:用于将文字封装成对象
                Checkbox:复选框
                TextComponent:
                        TextArea:文本框
                        TextField:文本区


三、布局管理器
    1、容器中的组件的排放方式,就是布局。
    2、常见的布局管理器:
            **FlowLayout(流式布局管理器),Panel默认的布局管理器,从左到右的顺序排列。默认水平居中
            **BorderLayout(边界布局管理器),Frame默认的布局管理器,东南西北中。默认居中
            **GridLayout(网络布局管理器),规则的矩阵
            **CardLayout(卡片布局管理器),选项卡
            **GridBagLayout(网格包布局管理器),非规则的矩阵


/*
创建图形化界面
1、创建frame窗体
2、对窗体进行基本设置,大小、位置、布局
3、定义组件
4、将组件通过窗体的add方法添加到窗体中
5、让窗体显示,通过setVisible(true)
*/
import java.awt.*;
class AwtDemo
{
        public  static void main(String[] args)
        {
        Frame f = new Frame("my awt");
f.setSize(500,400);//设置大小,长宽
f.setLocation(300,200);//设置窗体位置,窗体左上角点距离左侧300,距离上侧200
f.setLayout(new FlowLayout());//设置Frame的布局管理器为FlowLayout
Button  b = new Button("这里设置button名称");
f.add(b);

        f.setVisible(true);
        System.out.println("hello world");
}
}

四、事件监听机制特点
    **事件源(组件)
    **事件(Event)
    **监听器(Listener )
    **事件处理(引发事件后处理方式)

事件源:就是awt包或者swing包中的那些图形界面组件。
事件:每一个事件源都有自己特有的对应事件和共性事件
监听器:将可以触发某一个事件的动作(不只一个动作)都已经封装到了监听器中。
以上三者,在java中都已经定义好了,直接获取器对象来用就可以了。我们需要做的就是对产生的动作进行处理。

import java.awt.*;
import java.awt.event.*;
class AwtDemo
{
        public  static void main(String[] args)
        {
        Frame f = new Frame("my awt");
f.setSize(500,400);//设置大小,长宽
f.setLocation(300,200);//设置窗体位置,窗体左上角点距离左侧300,距离上侧200
f.setLayout(new FlowLayout());//设置Frame的布局管理器为FlowLayout
Button  b = new Button("这里设置button名称");
f.add(b);

f.addWindowListener(new MyWin());
        f.setVisible(true);
        System.out.println("hello world");
}
}
/*
class MyWin implements WindowListener
{
        //覆盖7个方法,可是我们只用到了关闭的动作,其他动作都没有用,可是却必须复写,因此实现接口不合适。
}
*/
//因为WindowListener的子类WindowAdapter已经实现了WindowListener接口,
//并覆盖了其中所有方法,那么我们只要继承WindowAdapter覆盖所需要的方法即可
class MyWin extends WindowAdapter
{
        public void windowClosing(WindowEvent e)
        {
                System.out.println("window closing----"+e.toString());
                System.exit(0);//退出程序,也就是关闭窗口
        }
        public void windowActivated(WindowEvent e)//激活状态,这里指窗体处于最前端
        {
                System.out.println("active");
        }
        public void windowOpened(WindowEvent e)//一打开就执行的动作
        {
                System.out.println("windowopen");
        }
}

五、Action事件
import java.awt.*;
import java.awt.event.*;
class FrameDemo
{
        private Frame f;
        private Button but;
        FrameDemo()
        {
                init();
        }
        public void init()
        {
                f = new Frame("my frame");
                f.setBounds(300,100,500,400);
                f.setLayout(new FlowLayout());
                but = new Button("my button");
                //将组件添加到frame中
                f.add(but);
                myEvent();
                f.setVisible(true);
        }
        private void myEvent()
        {
                f.addWindowListener(new WindowAdapter()
                {
                        public void windowClosing(WindowEvent e)
                        {
                                System.exit(0);
                        }
                });
                 //让按钮具备退出程序的功能
                /*
                按钮就是事件源,该选择哪个监听器?
                通过关闭窗体,了解到想要知道哪个组件具备什么特有监听器,需要查看该组件对象的功能。
                Button的描述,addActionListener

                ActionListener,是少有的没有适配器的接口
                */
                button.addActionListener(new ActionListener()//给button添加监听器
                {
                        public void actionPerformed(ActionEvent e)
                        {
                                System.out.println("button  exit()");
                                System.exit(0);
                        }
                });
        }
        public static void main(String[] args)
        {
                new FrameDemo();
        }
}

六、共性事件,鼠标  键盘事件
import java.awt.*;
import java.awt.event.*;
class MouseAndKeyEvent
{
          private Frame f;
        private Button but;
        private TextField tf;
         MouseAndKeyEvent ()
        {
                init();
        }
        public void init()
        {
                tf=new TextField(20);
                f = new Frame("my frame");
                f.setBounds(300,100,500,400);
                f.setLayout(new FlowLayout());
                but = new Button("my button");
                //将组件添加到frame中
                f.add(but);
                f.add(tf);
                myEvent();
                f.setVisible(true);
        }
        private void myEvent()
        {
                //判断输入到TextField中的内容是否是数字0-9
                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();//使用此事件,以便不会按照默认的方式由产生此事件的源代码来处理此事件
                                                            //输入0-9没问题,但是输入其他字母后,不复合条件,虽然不复合,但默认方式
                                                            //还是将字母继续输入,而e.consume()就是禁止字母继续输入
                                }
                                
                        }
                });
                //给but加上键盘监听器
                but.addKeyListener(new KeyAdapter( )
                {
                        public void keyPressed(KeyEvent e)
                        {
                                //获得的是键盘上按的键,及其码,下方代码只能返回单字母键,shift等多字母键无法返回
                                System.out.println( e.getKeyChar()+"..."+e.getKeyCode());
                                //返回多字母键
                                System.out.println( KeyEvent.getKeyText(e.getKeyCode()));
                                //按ESC退出窗口,ESC的code为27
                                if(e.getKeyCode()==27)
                                        System.exit(0);
                                //按ESC退出窗口,ESC的常量为:VK_ESCAPE
                                if(e.getKeyCode()==KeyEvent.VK_ESCAPE)
                                        System.exit(0);
                                //组合键,按ctrl+enter,按两个键的处理方式,原理:按下ctrl不动,再按enter
                                //方法isControlDown()判断ctrl键是否被按下,
                                if (e.isControlDown()&&e.getKeyCode()==KeyEvent.VK_ENTER)
                                        System.out.println("ctrl+enter");
                        }
                });
                f.addWindowListener(new WindowAdapter()
                {
                        public void windowClosing(WindowEvent e)
                        {
                                System.exit(0);
                        }
                });
                //button上两个监听,addMouseListener中的mouseClick 与addActionListener,这两个动作都能让button活动,但是同时存在时,mouseClick先执行,action后执行。但是一般最好加addActonListener,因为了这个后,键盘也可以让button活动
                but.addMouseListener(new MouseAdapter()
                {
                        private int count = 1;
                        private int clickCount = 1;
                        public void mouseEntered(MouseEvent e)
                        {
                                System.out.println("mouse enter component"+count++);
                        }
                        public void mouseClicked(MouseEvent e)
                        {
                                System.out.println("mouse click"+clickCount++);
                                       //鼠标双击动作,方法getClickCount获取点击次数
                                         if(e.getClickCount()==2)
                                                    System.out.println("double clicked");
                        }
                        
                });
                    but.addActionListener(new ActionListener()
                    {
                            public void  actionPerformed(ActionEvent e)
                            {
                                    System.out.println("action on");
                            }
                    });
        }
        public static void main(String[] args)
        {
                new MouseAndKeyEvent();
        }
}


练习:在文本框中输入目录,点击转到按钮,将该怒路中的文件与文件名称列在下面的文本域中
import java.awt.*;
import javaawt.event.*;
import java.io.*;
class MywindowDemo 
{
        private frame if;
        private Textfield tf;
        private Button but;
        private TextArea ta;
         private Dialog d;
        private Label lab;
        private Button okbut;
        MywindowDemo()
        {
                init();
        }
        public void init()
        {
                f=new Frame("my window");
                f.setBounds(300,100,600,500);
                f.setLayout(new FlowLayout());
                tf = new TextField(60);
                but = new Button("转到");
                ta = new TextArea(25,47);
                d = new Dialog(f,"提示信息",true);//true 的意思就是不点掉该窗体,不能进行其他操作
                 d.setBounds(400,200,200,50 );
                d.setLayout(new FlowLayout());
               lab = new Label();
                okbut = new Button("sure");
                d.add(lab);
                d.add(okbut);
                f.add(tf);
                f.add(but);
                f.add(Ta);
                myEvent();
                f.setVisible(true);
        }
        public void myEvent()
        {
                okbut.addActionListener(new ActionListener()
                {
                        public void actionPerformed(ActionEvent e )
                        {
                                d.setVisible(false);
                        }
                });
                d.addWindowListener(new windowAdapter()
                {
                         public void windowClosing(WindowEvent e)
                        {
                                d.setVisible(false);
                        }   
                });
                but.addActionListener(new ActionListener()
                {
                        public void actionPerformed(ActionEvent e)
                        {
                               showDir();
                        }
                });
                tf.addKeyListener(new KeyAdapter()
                {
                        public void keyPressed(KeyEvent e)
                        {
                                public void windowClosing(WindowEvent e)
                                {
                                        if(e.getKeyCodes()==KeyEvent.VK_ENTER);
                                        {
                                                showDir();
                                        }
                                }
                        }
                });
                f.addWindowListener(new WindowAdapter()
                {
                        public void windowClosing(WindowEvent e)
                        {
                                System.exit(0);
                        }
                });
        }
        private void showDir()
        {
                  String dirPath = tf.getText();
                                File dir = new File(dirPath);
                                if(dir.exists()&&dir.isDirectory())
                                {
                                        ta.setText("");
                                        String[] names=dir.list();
                                        for(String name:names)
                                        {
                                                  ta.append(name+"\r\n");
                                        }
                                }else
                                {
                                        String info= "info :+dirPath+"....error";
                                        lab.setText(info);
                                        d.setVisible(true);
                                }
                                tf.setText("");
        }
        public static void main(String[] args)
        {
                new MywindowDemo();
        }
}


练习:菜单+双击jar包执行
package mymenu;//带包编译,命令行中    javac  -d  c:\myclass  MyMenuDemo.java
                                   //打jar包                      jar -cwf my.jar mymenu
                                    //配置文件,建一个1.txt,内容:Main-Class: mymenu.MyMenuDemo
                                                                                                                包    主函数类
                        //注意:Main-Class: 后有一个空格(标准格式),主函数类后有回车(表示该行结束)。
                        //如果没加空格,出现IO异常;如果没有enter,那么1.txt中内容配置不到jar配置文件中。
                        //建完配置文件,目的是告诉jar包主函数类是哪个,因此命令行
                        //jar -cvfn my.jar 1.txt mymenu
                        //另外jar文件需要在本地注册才可以使用,如果是双击安装的jdk就可以不用此步骤
                        //如果是复制过来的jdk目录,需要自己配置,工具-文件夹选项-文件类型-新建jar-高级-新建open-浏览   D:\jdk1.6.0_45\bin\javaw.exe -jar        这样就可以了
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class MyMenuDemo
{
        private Frame f;
        private TextArea ta;
        private MenuBar mb;
        private Menu m;
        private MenuItem closeItem;
        private MenuItem subItem;
        private MenuItem openItem;
        private MenuItem saveItem;
        private Menu subMenu;
        private FileDialog openDia,saveDia;

        File file;
        MyMenuDemo()
        {
                init();
        }
        public void init()
        {
                f = new Frame("my window");
                f.setBounds(400,300,400,300);
                f.setLayout(new FlowLayout());
                mb =new MenuBar();
                ta= new TextArea();
                m = new Menu("file");
                subMenu = new Menu("子菜单");
                subItem = new MenuItem("sub item");
                closeItem = new MenuItem("eixt");
                openItem = new MenuItem("open");
                saveItem = new MenuItem("save");
                openDia = new FileDialog(f,"open",FileDialog.LOAD);
                saveDia = new FileDialog(f,"save",FIleDialog.SAVE);

                subMenu.add(subItem);
                m.add(closeItem);
                m.add(openItem);
                m.add(saveItem);
                m.add(subMenu);
                mb.add(m);
                
                f.setMenuBar(mb);
                f.add(ta);
                myEvent();
                f.setVisible(true);
                
        }
        public void myEvent()
        {
                saveItem.addActionListener(new ActionListener()
                {
                        public void actionPerformed(ActionEvent e)
                        {
                                if(file==null)
                                {
                                saveDia.setVisible(true);
                                String dirPath = saveDia.getDirectory();
                                String fileName = saveDia.getFile();
                                if(dirPath==null  ||   fileName ==null)
                                        return;
                                file = new File(dirPath,fileName);
                                }
                                try
                                {
                                        BufferedWriter bufw = new BufferedWriter(new FileWriter(file));
                                        String text = ta.getText();
                                        bufw.write(text);
                                        bufw.close();
                                }
                                catch(IOException ie)
                                {
                                        throw new RuntimeException();
                                }
                        }
                });
                openItem.addActionListener(new ActionListener()
                {
                        public void actionPerformed(ActionEvent e)
                        {
                                openDia.setVisible(true);
                                String dirPath = openDia.getDirectory();
                                String fileName=openDia.getFile();
                                if(dirPath ==null | fileName ==null)
                                            return ;

                                ta.setText();
                               file = new File(dirPath,fileName);
                                try
                                {
                                        BufferedReader bufr = new BufferedReader(new FileReader(file));
                                        String line = null;
                                        while((line = bufr.readLine())!=null0
                                        {
                                                ta.append(line+"\r\n");
                                        }
                                }
                                catch(IOException e)
                                {
                                        throw new RuntimeException("read failed");
                                }
                        }
                });
                closeItem.addActionListener(new ActionListener()
                {
                        public void actionPerformed(ActionEvent e)
                        {
                                System.exit(0);
                        }
                });
                f.addWindowListener(new WindowAdapter()
                {
                        public void windowClosing(WindowEvent e)
                        {
                                System.exit(0);
                        }
                });
        }
        public static void main(String[] args)
        {
                new MyMenuDemo();
        }
}

















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值