分享

Java笔记(八 图形界面编程)

 依笑乘風涼 2007-05-09

Java笔记(八 图形界面编程)

    AWT(Abstract Windows Toolkit),抽象窗口工具包,SUN公司提供的用于图形界面编程(GUI)的类库。基本的AWT库处理用户界面元素的方法是把这些元素的创建和行为委托给每个目标平台上(Windows、Unix、Macintosh等)的本地GUI工具进行处理。例如:如果我们使用AWT在一个Java窗口放置一个按钮,那么实际上是用的是一个具有本地外观和感觉的按钮。这样,从理论上来说,我们说编写的图形界面程序能运行在任何平台上,做到了图形界面程序的跨平台运行
    Component是Java中所有图形界面组件的一个基类
    Container是Component的子类,一个容器(Container)是可以容纳其他组件的组件
    Window继承了Container,A Window object is a top-level window with no borders and no menubar.
    Frame继承自Window,A Frame is a top-level window with a title and a border。要产生一个图形界面的程序,首先就要产生一个框架窗口
    布局管理器
        容器里组件的位置和大小是由布局管理器来决定的。容器对布局管理器的特定实例保持一个引用。当容器需要定位一个组件时,它将调用布局管理器来完成。当决定一个组件的大小时,也是如此
        在AWT中,给我们提供了五种布局管理器:BorderLayout(缺省)、FlowLayout、GridLayout、CardLayout、GridBagLauout
    AWT事件模型
       Events(事件):描述发生了什么的对象
       Event source(事件源):事件的产生器
       Event handlers(事件处理器):接收事件对象、解释事件对象并处理用户交互的方法
       委托模型:事件监听器是实现了监听器接口(java.awt.event中的WindowListenter)的类。一个监听器对象是一个实现了专门的监听器接口的类的实例
import java.awt.*;
import java.awt.event.*;
public class MyFrame
{
   public static void main(String[] args)
   {
      Frame f=new Frame("llilac");//Frame(String title):Constructs a new, initially invisible Frame object with the specified title.
      f.setSize(600,400);//public void setSize(int width,int height):Resizes this component so that it has width width and height height.
      f.setLocation(100,100);//左上角是计算机屏幕的原点public void setLocation(int x,int y):Moves this component to a new location. The top-left corner of the new location is specified by the x and y parameters in the coordinate space of this component‘s parent.
      f.setBackground(Color.GREEN);//public void setBackground(Color c):Sets the background color of this component.
      //f.setLayout(new BorderLayout(10,10));//缺省布局管理器BorderLayout
      //f.setLayout(new FlowLayout(FlowLayout.LEFT));
      f.setLayout(new GridLayout(3,2,10,10));//3行2列,垂直水平间隙为10
     
      Button btn1=new Button("hi");//Button(String label):Constructs a Button with the specified label.
      Button btn2=new Button("hello");
      Button btn3=new Button("Nice");
      Button btn4=new Button("to");
      Button btn5=new Button("metting");
      f.add(btn1,"North");//void add(Component comp, Object constraints):Adds the specified component to the end of this container.
      f.add(btn2,"South");
      f.add(btn3,"West");
      f.add(btn4,"East");
      f.add(btn5,"Center");//要在f.show()前面
      //f.addWindowListener(new MyWindowListener());//注册一个事件监听器
      //f.addWindowListener(new YouWindowListener());
      f.addWindowListener(new WindowAdapter()//用匿名的内部类,因为WindowAdapter是抽象类,所以加上{}进行实现。采用此种方法时,不再需要MyWindowListener类和YouWindowListener类
                          {
                              public void windowClosing(WindowEvent e) //Invoked when the user attempts to close the window from the window‘s system menu.
                               {
                                    System.exit(0);
                               }
                          });
      f.show();//继承自Window,public void show():Makes the Window visible. If the Window and/or its owner are not yet displayable, both are made displayable. The Window will be validated prior to being made visible. If the Window is already visible, this will bring the Window to the front.还有一个方法,是继承自Component,public void setVisible(boolean b):Shows or hides this component depending on the value of parameter b. 但这个方法只能让窗口可见,不能让窗口到最前面
   }
}
class MyWindowListener implements WindowListener//定义了一个事件监听器类
{
   public void windowActivated(WindowEvent e)
   {
    
   }
   public void windowClosed(WindowEvent e)//用来对窗口已经关闭之后的事件进行响应Invoked when a window has been closed as the result of calling dispose on the window. 
   {
     
   }
   public void windowClosing(WindowEvent e) //Invoked when the user attempts to close the window from the window‘s system menu.
   {
          System.exit(0);
   }
   public void windowDeactivated(WindowEvent e)
   {
    
   }
   public void windowDeiconified(WindowEvent e)
   {
    
   }
   public void windowIconified(WindowEvent e)
   {
    
   }
   public void windowOpened(WindowEvent e)
   {
    
   } 
}//如果用的是实现接口的话,就要实现接口中所有的类。这样很麻烦。于是Java提供了一种类叫适配器类,接口WindowListener对应的适配器类是WindowAdapter,它实现了WindowListener的所有方法,但都是空实现。
class YouWindowListener extends WindowAdapter//Java把适配器类WindowAdapter声明为abstract,因为它对接口方法的实现都是空实现,所以直接实例化适配器的一个类是没有意义的,所以Java把他声明为了abstract,以防用户直接实例化。我们只要直接从适配器类WindowAdapter派生一个子类就行了
{
   public void windowClosing(WindowEvent e) //Invoked when the user attempts to close the window from the window‘s system menu.
   {
          System.exit(0);
   }
}
-----------------------------------------------------------------------------
//实现Win记事本部分功能
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class HisFrame//创建菜单:菜单栏(MenuBar类)-菜单(Menu类)-菜单项(MenuItem类)
{
   public static void main(String[] args)
   {
      final Frame f=new Frame("http://llilac");
      f.setSize(600,400);
      f.setLocation(100,100);
      /*构造文本域,只能存放单行文本
      TextField tf=new TextField(20);
      f.add(tf,"North");
      */
      final TextArea tf=new TextArea();
      f.add(tf);
      f.addWindowListener(new WindowAdapter()//窗口监听器
                          {
                              public void sindowClosing(WindowEvent e)
                              {
                                System.exit(0); 
                              } 
                          });
                         
      MenuBar mb=new MenuBar();
      Menu m1=new Menu("File");
      Menu m2=new Menu("Edit");
      MenuItem mi1=new MenuItem("New");
      MenuItem mi2=new MenuItem("open");
      mi2.addActionListener(new ActionListener()//打开文件功能
                            {
                               public void actionPerformed(ActionEvent e)
                               {
                                  FileDialog fd=new FileDialog(f,"Open File Dialog",FileDialog.LOAD);//public FileDialog(Frame parent,String title,int mode):parent - the owner of the dialog;title - the title of the dialog;mode - the mode of the dialog; either FileDialog.LOAD or FileDialog.SAVE
                                  fd.show();
                                  /*把文件的内容读进来,此时只能读入当前目录下的文件,因为getFile()知识返回文件名,构建输入流后它只在当前目录下查找,所以要想读取其它目录的文件,要给出路经
                                  String strFile=fd.getFile();
                                  if(strFile!=null)
                                  {
                                    try
                                    {
                                       FileInputStream fis=new FileInputStream(strFile);
                                       byte[] buf=new byte[10*1024];
                                       int len=fis.read(buf);
                                       tf.append(new String(buf,0,len)); 
                                       fis.close();
                                    } 
                                    catch (Exception ex)
                                    {ex.printStackTrace();}
                                  }
                                  */
                                  //把文件的内容读进来,此时可以读取其它目录的文件,因为给出了路经
                                  String strFile=fd.getDirectory()+fd.getFile();//获取的是完整的路径名
                                  if(strFile!=null)
                                  {
                                    try
                                    {
                                       FileInputStream fis=new FileInputStream(strFile);
                                       byte[] buf=new byte[10*1024];
                                       int len=fis.read(buf);
                                       tf.append(new String(buf,0,len));
                                       fis.close(); 
                                    } 
                                    catch (Exception ex)
                                    {ex.printStackTrace();}
                                  }
                                 
                               }
                            });
      MenuItem mi3=new MenuItem("save");
      MenuItem mi4=new MenuItem("exit");
      mi4.addActionListener(new ActionListener()//退出功能
                            {
                               public void actionPerformed(ActionEvent e)
                               {
                                  System.exit(0); 
                               }
                            });
      MenuItem mi5=new MenuItem("copy");
      MenuItem mi6=new MenuItem("paste");
     
      m1.add(mi1);
      m1.add(mi2);
      m1.add(mi3);
      m1.add(mi4);
      m2.add(mi5);
      m2.add(mi6);
      mb.add(m1); 
      mb.add(m2);
     
      f.setMenuBar(mb); 
      f.show();
   }
}
--------------------------------------------------------------------------------
java.awt包中还有一些表较常用的组件,比如choice—下拉列表框;Checkbox—复选框;Label—标签

    Java基础类
      JFC(Java foundation Classes):Java基础类,是关于GUI组件和服务的完整集合,主要包括5个API:AWT、Java2D、Accessiblility、Drag&Drop、Swing。JFC提供了帮助开发人员设计复杂应用程序的一整套应用程序开发包
      Java2D是一图形API,它为Java应用程序提供了一套高级的有关二维(2D)图形图像处理的类,Java2D API扩展了java.awt和java.awt.image类,并提供了丰富的绘图风格,定义了复杂图形的机制和精心调节绘制过程的方法和类。这些API使得独立于平台的图形应用程序的开发更加简便
      Accessiblility API提供了一套高级工具,用以辅助开发使用非传统输入和输出的应用程序。它提供了一个辅助的技术接口,如:屏幕阅读器,屏幕放大器,听觉文本阅读器(语音处理)等等
      Drag&Drop技术提供了Java和本地应用程序之间的互操作性,用来在Java应用程序和不支持Java技术的应用程序之间交换数据
      JFC模块的重点在Swing。Swing用来进行基于窗口的应用程序开发,它提供了一套丰富的组件和工作框架,以指定GUI如何独立于平台地展现其视觉效果

    javax.Swing中的组件都是以JComponent这个类为基类的
import javax.swing.*;
public class SwingTest
{
  public static void main(String[] args)
  {
    JFrame jf=new JFrame("llilac");
    jf.setSize(600,400);
    jf.setLocation(100,100);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//public static final int EXIT_ON_CLOSE:The exit application default window close operation.
    JButton btn=new JButton("l");
    jf.getContentPane().add(btn,"West");//首先获取一个内容面板,然后将组件增加到内容面板上
    jf.show();
  }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约