java_GUI

本文详细介绍Java AWT和Swing库的使用方法,包括组件介绍、布局管理、事件监听等核心概念,并通过具体示例展示如何创建图形界面应用程序。

 

GUI

GUI

java.Awtjavax.Swing

java.Awt:依赖平台。系统不一样,效果

javax.Swing:基于Awt。跨平台,

xwt包:

Button:按扭

Label:标签

Checkbox:复选框

TextComponen:文本组件

Container:容器、组件,该组件里还可以再添加组件。

Panel:面板

Frame:框架

Dialog:对话框

 

布局:组件的排放方式。

流式布局:从左到右,默认居中。

边界布局:上北下南,左西右东,中间。

格子布局:计算器。

网格包布局:一个按扭占多个格子。

卡片式布局:选项卡。

坐标式布局:放哪随便。

Frame默认的布局:边界式布局。

Frame f = new Frame();

Frame f = new Frame("my awt");

f.setSize(500,100);500横坐标,100纵坐标。

f.setLocation(300,200);300顶点距上边,200下点边距下边。

f.setLayout(new FlowLayout());设置成流式布局。

Button b = new Butten("按扭");

f.add(b);

图形化界面是主线程外,另外一个线程执行的。

f.setVisible(true);可视。

创建图形化界面:

       1、创建Frame窗体。

       2、对窗体进行基本设置。比如大小、位置、布局。

       3、定义组件。

       4、将组件通过窗体的add方法添加到窗体中。

       5、让窗体显示,通过setVisible(true)

 

事件监听机制:

事件监听机制流程图:

事件监听机制的特点:

       1、事件源:awt包、swing包中的那么图形界面组件。

       2、事件:每一个事件源都有自己特有的对应事件和共性事件。

       3、监听器:将可以触发某一个事件的动作(不止一个)都已经封装到了监听器中。

       4、事件处理:

123都在java中定义好了,直接获取对象来用就可以了。

我们要做的是对产生的动作进行处理。

窗体事件:

Frame f = new Frame();

Frame f = new Frame("my awt");

f.setSize(500,100);500横坐标,100纵坐标。

f.setLocation(300,200);300顶点距上边,200下点边距下边。

f.setLayout(new FlowLayout());设置成流式布局。

Button b = new Butten("按扭");

f.add(b);

f.addWindowListener();

接口 WindowListener:里边7个全抽象方法。要实现它必须覆盖7个方法。

类 WindowAdapter此类实现了WindowListener接口,覆盖了它的7个方法,但每个方法都是空的。

这时自定义一个监听器,继承WindowAdapter,就可以单独创造事件处理。覆盖所需要的方法就可以了。

f.addWindowListener(new WindowAdapter(){

         public void windowClosing(WindowEvent e){

            System.out.println("window closing");//处理事件。

            System.exit(0);//关闭程序,就关闭窗口。

         }

         //处于最前端就处于Activated状态。

         public void windowActivated(WindowEvent e){

            System.out.println("active");

         }

         //一打开就处于这个动作。

         public void windowOpened(WindowEvent e){

            System.out.println("我被打开了");

         }

      });

}

Action事件:

定义该图形中所需的组件的引用。

让按钮具备退出程序的功能:

   按钮就是事件源。

   那么选择哪个监听器呢?

   通过关闭窗体示例了解到,想要知道哪个组件具备什么样的特有监听器,需要查看该组件对象的功能。

Button组件:

   通过查阅,发现按钮支持一个特有监听addActionListener活动监听。

   少数没有识别器的其中一个。只要方法超过3个,几乎都有识别器。

but.addActionListener(new ActionListener(){

   publicvoid actionPerformed(ActionEvent ae){

      System.out.println("退出,按扭触发的");

      System.exit(0);

   } 

});

示例:

class FrameTest{

   private Framef;

   private Buttonbut;

   FrameTest(){

      init();

   }

   public void init(){

      f = new Frame("my frame");

      //frame进行基本设置。

      f.setBounds(300,200,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);

         }

      });  

   //按扭监听机制。

      but.addActionListener(new ActionListener(){

         public void actionPerformed(ActionEvent ae){

            System.out.println("退出,按扭触发的");

            System.exit(0);

         }    

      });

}

   public static void main(String[] args){

      new FrameTest();

   }

}

鼠标事件:

   Component组件:

   but.addMouseListener(new MouseAdapter(){

         private int count = 1;

         private int clickCount = 1;

         //鼠标进入动作。

         public void mouseEntered(MouseEvent e){

            System.out.println("鼠标进入到该组件中"+count++);

         }       

         //鼠标点击动作。

         public void mouseClicked1(MouseEvent e){

            System.out.println("点击动作"+count++);

         }       

         //双击动作。

         public void mouseClicked(MouseEvent e){

            if(e.getClickCount()==2)

                System.out.println("双击动作"+clickCount++);

         }

      });

//按扭一活动就触发些动作。不管点击,或者敲回车。

      but.addActionListener(new ActionListener(){

         public void actionPerformed(ActionEvent e){

            System.out.println("actionok");

         }

      });

 

键盘事件:

but.addKeyListenner(new KeyAdapter(){

      public void keyPressed(KeyEvent e){

                System.out.println(e.getKeyChar()+".."+e.getKeyCode());

      //这时按键盘字母,就录出该字母。以及键对应的码。

               System.out.println(KeyEvent.getKeyText(e.getKeyCode())+".."+e.getKeyCode());             

                  //这时键盘一按ESC,就关闭程序。ESC对应码为27

                if(e.getKeyCode()==27)   //记不住27if(e.getKeyCode()==KeyEvent.VK_ESCAPE)

                   System.exit(0);            

                //  组合键,如:CtrlEnter同时按。

                   if(e.isControlDown() &&e.getKeyCode()==KeyEvent.VK_ENTER)  

                      System.out.println("ctrl+enter is run");

                   System.exit(0);            

            }

         });

tf = new TextField(20);

f.add(tf);

tf.addKeyListener(new KeyAdapter(){

   public void keyPressed(KeyEvent e){

      int code = e.getKeyCode();

      //判断键盘录入的是0~9的数,如果不是,不让进。

      if(!(code>=KeyEvent.VK_0 &&code<=KeyEvent.VK_9)){

         System.out.println(code+".....是非法的");

         e.consume();

      }

   }

});

练习:列出指定目录的内容。

package GUI_Test;

import java.awt.*;

import java.awt.event.*;

import java.io.File;

 

public class GUI_List_Test {

   private Framef//窗体

   private TextFieldtf //单行文本

   private Buttonbut//按扭1

   private TextAreata//文本区域

  

   private Dialogd//对话框

   private Labellab//标签

   private ButtonokBut; //按扭2

  

   GUI_List_Test(){

      init();

   }

  

   public void init(){

      f = new Frame("我的窗口");

      f.setBounds(200,200,600,500); //距左边200,距右边200,横600,纵500

      f.setLayout(new FlowLayout()); //流式布局  

      tf = newTextField(60);  //单行文本,60列数  

      but = new Button("转到");   

      ta = new TextArea(25,70); //行数,列数

     

      d = new Dialog(f,"提示信息",true);

      d.setBounds(500, 300, 250, 150);//对话框的大小

      d.setLayout(new FlowLayout());//对话框的流式布局

      lab = new Label();

      okBut = new Button("确定");

     

      d.add(lab);

      d.add(okBut);

     

      f.add(tf);

      f.add(but);

      f.add(ta);

     

      myEvent();

      f.setVisible(true);

   }

     

      private 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);

            }

         });        

         //单行文本回车键的事件处理

         tf.addKeyListener(new KeyAdapter(){

            public void keyPressed(KeyEvent e){

                if(e.getKeyCode()==KeyEvent.VK_ENTER)

                   showDir();

            }

         });

         //窗体上的转到按扭的事件处理

         but.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e){

                showDir();              

            }

         });

         //关闭程序事件处理

         f.addWindowListener(new WindowAdapter(){

            public void windowClosing(WindowEvent e){

                System.exit(0);

            }

         });

      } 

   //显示目录

   private void showDir(){

      //按扭被按时,将tf内的字符存到dirPath

      String dirPath = tf.getText();

      File dir = new File(dirPath); 

      //判断dir是不是目录,存不存在

      if(dir.exists() && dir.isDirectory()){

         ta.setText("");//每触发一次事件后,都将文本区域清空。

         String[] names = dir.list();

         for(String name : names){

            //目录存在,就将它的子目录返到ta文本区域

            ta.append(name+"\r\n");

         }

      }else{

         //对话框上出现的文字信息

         String info = "你输入的信息:"+dirPath+"有错误,请重新输入!";

         lab.setText(info);//将信息添加到对话框上

         d.setVisible(true);

      }

   }

  

   public static void main(String[] args) {

      new GUI_List_Test();

   }

}

练习:制作记事本程序。

package GUI_Test;

import java.awt.*;

import java.awt.event.*;

import java.io.*;

 

public class NoteBookTest{

   private Framef//窗体

   private MenuBarbar//菜单栏

   private TextAreata//文本区域

   private MenufileMenu//菜单栏中的文件菜单

   private MenuItemopenItem,saveItem,closeItem;//子菜单

 

   private FileDialogopenDia,saveDia;//文件对话框,打开文件、保存文件时的对话框

 

   private Filefile;//文件流

   NoteBookTest(){

      init();

   }

   public void init(){

      f = new Frame("my window"); //窗体对象

      f.setBounds(300,100,650,600);//窗体大小

 

      bar = new MenuBar();//菜单栏实例

      ta = new TextArea();//文本区域实例

 

      fileMenu = new Menu("文件");

     

      openItem = new MenuItem("打开");

      saveItem = new MenuItem("保存");

      closeItem = new MenuItem("退出");

      //把打开文件、保存文件、关闭3子菜单添加到文件根菜单

      fileMenu.add(openItem);

      fileMenu.add(saveItem);

      fileMenu.add(closeItem);

      bar.add(fileMenu);//把文件根菜单添加进菜单栏

 

      f.setMenuBar(bar);//把菜单栏加到窗体

 

      openDia = new FileDialog(f,"我要打开",FileDialog.LOAD);//查找要读取的文件

      saveDia = new FileDialog(f,"我要保存",FileDialog.SAVE);//查找要写入的文件

 

      f.add(ta);//添加文本区域进窗体

      myEvent();//事件

 

      f.setVisible(true);

   }

   private 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.flush();

                bufw.close();

            }

            catch (IOException ex){

                throw new RuntimeException();

            }          

         }

      });

      //打开文件事件

      openItem.addActionListener(new ActionListener(){

         public void actionPerformed(ActionEvent e){

            openDia.setVisible(true);//显示

            String dirPath = openDia.getDirectory();//获取目录

            String fileName = openDia.getFile();//获取文件名

//          System.out.println(dirPath+"..."+fileName);

            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())!=null)  {

                   ta.append(line+"\r\n");//将文件文本内容添加到文本区域

                }

               

                bufr.close();

            }catch (IOException ex){

                throw new RuntimeException("读取失败");

            }

         }

      });

      //退出按扭事件

      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 NoteBookTest();

   }

}

 

如何制作可以双击执行的jar包呢?

1,将多个类封装到了一个包(package)中。

2,定义一个jar包的配置信息。

   定义一个文件a.txt 。文件内容内容为:

   Main-Class:(空格)包名.类名(回车)

3,打jar包。

   jar -cvfm my.jara.txt 包名

4,通过winrar程序进行验证,查看该jar的配置文件中是否有自定义的配置信息。

5,通过工具--文件夹选项--文件类型--jar类型文件,通过高级,定义该jar类型文件的打开动作的关联程序。

   jdk\bin\javaw.exe-jar

6,双击试试!。哦了。

 



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值