9.Java图形用户界面设计 Java 语言程序设计第2版 电子教案

上传人:新** 文档编号:568242502 上传时间:2024-07-23 格式:PPT 页数:141 大小:1.21MB
返回 下载 相关 举报
9.Java图形用户界面设计 Java 语言程序设计第2版 电子教案_第1页
第1页 / 共141页
9.Java图形用户界面设计 Java 语言程序设计第2版 电子教案_第2页
第2页 / 共141页
9.Java图形用户界面设计 Java 语言程序设计第2版 电子教案_第3页
第3页 / 共141页
9.Java图形用户界面设计 Java 语言程序设计第2版 电子教案_第4页
第4页 / 共141页
9.Java图形用户界面设计 Java 语言程序设计第2版 电子教案_第5页
第5页 / 共141页
点击查看更多>>
资源描述

《9.Java图形用户界面设计 Java 语言程序设计第2版 电子教案》由会员分享,可在线阅读,更多相关《9.Java图形用户界面设计 Java 语言程序设计第2版 电子教案(141页珍藏版)》请在金锄头文库上搜索。

1、9.1图形用户界面设计概述v9.1.1 GUI支持包和简单GUI程序例v1.java.awt包 vJava语言在java.awt包中提供了大量地进行GUI设计所使用的类和接口,包括绘制图形、设置字体和颜色、控制组件、处理事件等内容,AWT是Java语言进行GUI程序设计的基础。v2. javax.swing包vSwing包是Java基础类库(Java Foundation Classes,JFC)的一部分。Swing提供了从按钮到可分拆面板和表格的所有组件。vSwing组件是Java语言提供的第二代GUI设计工具包,它以AWT为基础,在AWT内容的基础上新增或改进了一些GUI组件,使得GUI程

2、序功能更强大,设计更容易、更方便。Swing是开发新组件的项目代码名,现在,这个名字常用来引用新组件和相关的API。vAWT组件和对应的Swing组件,从名称上很容易记忆和区别。例如,AWT的框架类、面板类、按钮类和菜单类,被命名为Frame、Panel、Button和Menu,而Swing对应的组件类被命名为JFrame、JPanel、JButton和JMenu。与AWT组件相比,Swing组件的名前多一个 “J” 字母。另 外 , AWT 组 件 在 java.awt包 中 ,而 Swing组 件 在javax.swing包中。v3.一个Java GUI简单程序v【例9.1】一个简单的Sw

3、ing GUI应用程序。在一个框架窗口中显示两个标签和一个按钮:上面的标签显示一串固定的文字信息,选择按钮后在下面的标签上显示系统现在的时间。import import java.awtjava.awt.*;.*;import import java.awt.eventjava.awt.event.*;.*;import import javax.swingjavax.swing.*;.*;import java.util.*;import java.util.*;/ / 继承JFrameJFrame类并实现ActionListenerActionListener接口public class

4、public class SwingDemoSwingDemo extends extends JFrameJFrame implements implements ActionListenerActionListener JButtonJButton b1; / b1; / 声明按钮对象 JLabelJLabel l1,l2; / l1,l2; / 声明标签对象SwingDemoSwingDemo() / () / 定义构造方法 super(Swing super(Swing应用程序的例);/ );/ 调用父类的构造方法 l1=new l1=new JLabelJLabel(一个GUIGUI

5、应用程序的例子 , , JLabel.CENTERJLabel.CENTER); / ); / 定义标签,文字居中 l2=new l2=new JLabelJLabel( ); / ( ); / 定义无文字标签 b1=new b1=new JButtonJButton(现在时间 T);/ T);/ 定义按钮 b1.setMnemonic(KeyEvent.VK_T);/ b1.setMnemonic(KeyEvent.VK_T);/ 设置按钮的快捷键 b1.setActionCommand(time); / b1.setActionCommand(time); / 设置控制名 b1.addAc

6、tionListener(this); / b1.addActionListener(this); / 注册按钮事件 add(l1,BorderLayout.NORTH); / add(l1,BorderLayout.NORTH); / 添加标签l1l1 add(l2,BorderLayout.CENTER); / add(l2,BorderLayout.CENTER); / 添加标签l2l2 add(b1,BorderLayout.SOUTH); / add(b1,BorderLayout.SOUTH); / 添加标签b1b1 / / 对按钮引发事件编程 public void public

7、 void actionPerformed(ActionEventactionPerformed(ActionEvent e) e) / / 捕获按钮事件 Calendar c1 = Calendar c1 = Calendar.getInstanceCalendar.getInstance();(); / / 获取系统日期和事件 if(e.getActionCommand().equals(timeif(e.getActionCommand().equals(time) / / 判断是否为所需的按钮事件 l2.setText( l2.setText(“现在时间是”+ + c1.get(Cal

8、endar.HOUR_OF_DAY) c1.get(Calendar.HOUR_OF_DAY) + +“时 ”+ +c1.get(Calendar.MINUTE)+c1.get(Calendar.MINUTE)+“分”);); / /设置标签文字 l2.setHorizontalAlignment(JLabel.CENTER); l2.setHorizontalAlignment(JLabel.CENTER); / / 设置标签标签文字居中对齐 else System.exit(0);else System.exit(0); public static void main(String pub

9、lic static void main(String argsargs)/ )/ 主方法 JFrame.setDefaultLookAndFeelDecorated(trueJFrame.setDefaultLookAndFeelDecorated(true);); / / 加此语句显示为运行结果图的右图 JFrameJFrame frame = new frame = new SwingDemoSwingDemo();(); / / 创建JFrameJFrame对象,初始不可见 frame.setDefaultCloseOperationframe.setDefaultCloseOpera

10、tion( ( JFrame.EXIT_ON_CLOSEJFrame.EXIT_ON_CLOSE);/ );/ 设置框架关闭按钮事件 frame.packframe.pack(); / (); / 压缩框架的显示区域 frame.setVisible(trueframe.setVisible(true); / ); / 显示框架主窗口 v程序运行后显示的形式如下图 。 vJava Swing GUI应用程序中的基本代码如下。v(1)引入合适的包和类v一般的Swing GUI应用程序应包含程序中的前三个引入语句,它们分别表示引入awt包、awt事件处理包和swing包。其他包按需引入。v由于Sw

11、ing组件使用AWT的结构,包括AWT的事件驱动模式,所以,使用swing组件的程序一般需要使用awt包。v(2)使用缺省的观感或设置自己的观感(Look and Feel)v(3)设置一个顶层的容器v(4)根据需要,使用缺省的布局管理器或设置另外的布局管理器v(5)定义组件并将它们添加到容器v(6)对组件或事件编码v9.1.2 容器、组件、布局和观感v1.容器(Container)和组件(Component)v一个Java的图形用户界面的最基本元素是组件,组件是可以以图形化的方式显示在屏幕上并能与用户进行交互的对象,如一个按钮、一个文本框等。在Java语言中,通常将组件放在一定的容器内使用。

12、容器实际上是一种具有容纳其他组件和容器的功能的组件。抽象类Container是所有容器的父类,其中包含了很多有关容器的功能和方法 。 而 类 Container又 是 Java语 言 的 组 件 类Component的子类。v2.布局管理器(Layout Manager)v为了使得图形用户界面具有良好的平台无关性,在Java语言中提供了布局管理器这个工具来管理组件在容器中的布局,而不使用直接设置组件位置和大小的方式。容器中的组件定位由布局管理器决定。每个容器都有一个缺省的布局管理器,当容器需要对某个组件进行定位或判断其大小尺寸时,就会调用其相应的布局管理器。但也可以不用缺省的布局管理器,在程序

13、中指定其新的布局管理器。vJava平台提供多种布局管理器,常用的有FlowLayout、BorderLayout、 GridLayout、CardLayout、BoxLayout和GridBagLayout等。使用不同的布局管理器,组件在容器上的位置和大小都是很不一样的。 v在程序中安排组件的位置和大小时,应该注意:v(1)容器中的布局管理器负责各个组件的大小和位置。因此用户无法在这种情况下直接设置这些属性。若试图使 用 Java语 言 提 供 的 setLocation()、 setSize()、 setBounds()等方法,则都会被布局管理器覆盖。v(2)若用户确实需要亲自设置组件的位置

14、和大小,则应取消该容器的布局管理器,方法为: setLayout(nullsetLayout(null););v随 后 , 用 户 必 须 使 用 setLocation()、 setSize()、 setBounds()等方法为组件设置大小和位置,但这种方法将会导致程序的系统相关。v在一个GUI应用程序的界面上,除了可以见到上述的标准GUI元素外,还可以见到一些非交互的起到装饰、美化界面的作用的几何图形、图案、图像等内容。v3.观感(Look and Feel)vJava swing的一个重要特征是它的可插入的“观感”体系。一个Swing应用程序或一个最终用户可指明所需要的观感,使得Swin

15、g应用程序的外观和行为都可以被定制。Swing运行一个缺省的Java观感(也称为Metal观感),还实现了模仿Motif和Windows的观感。这样,一个Swing程序可拥有Java程序的独特外观,也可以拥有熟悉的Windows操作系统外观。v在本章稍后部分的单选按钮的程序例中分别显示了Windows、Motif和Metal三种不同风格的观感。v一般在应用程序的JFrame的构造方法中或在JApplet的init()方法中进行观感的设置。v【例9.2】设置观感。import import javax.swingjavax.swing.*;.*;import import java.awtjav

16、a.awt.*;.*;public class public class SetLAFSetLAF public static void public static void setNativeLookAndFeelsetNativeLookAndFeel() () try try UIManager.setLookAndFeel(UIManagerUIManager.setLookAndFeel(UIManager. . getSystemLookAndFeelClassNamegetSystemLookAndFeelClassName();(); catch(Exception e) ca

17、tch(Exception e) System.out.printlnSystem.out.println(设置native LAFnative LAF错误: : + + e);e); public static void public static void setJavaLookAndFeelsetJavaLookAndFeel() () try try UIManager.setLookAndFeel(UIManagerUIManager.setLookAndFeel(UIManager. . getCrossPlatformLookAndFeelClassNamegetCrossPla

18、tformLookAndFeelClassName();(); catch(Exception e) catch(Exception e) System.out.printlnSystem.out.println(设置Java LAFJava LAF错误: + : + e);e); public static void public static void setMotifLookAndFeelsetMotifLookAndFeel() () try try UIManager.setLookAndFeelUIManager.setLookAndFeel( (“ com.sun.java.sw

19、ing.plafcom.sun.java.swing.plaf. . motif.MotifLookAndFeelmotif.MotifLookAndFeel);); catch(Exception e) catch(Exception e) System.out.printlnSystem.out.println(设置Motif LAFMotif LAF错误: + : + e);e); v因为setLookAndFeelsetLookAndFeel()方法抛出异常,因此设置观感的代码应捕捉异常。本例创建的类SetLAF可在以后的程序中设置观感时使用。v9.1.3事件处理v在一个GUI程序中,

20、为了能够接收用户的输入、命令的按键和鼠标操作,程序系统首先应该能够识别这些操作并做出相应的响应。通常一个键盘和鼠标操作将引发一个系统预先定义好的事件,用户程序只要编写代码定义每个事件发生时程序应做出何种响应即可。这些代码会在它们对应的事件发生时由系统自动调用,这就是GUI程序中事件和事件响应的基本原理。v在Java语言中,除了键盘和鼠标操作,系统的状态改变也可以引发事件。v可能产生事件的组件称为事件源,不同事件源上发生的事件种类是不同的。若希望事件源上引发的事件被程序处理,需要将事件源注册给能够处理该事件源上那种事件类型的监听器。监听器具有监听和处理某类事件的功能,它可以是包容事件源的容器,也

21、可以是另外的对象。也就是说,事件源和事件处理是分开的,一般组件都不处理自己的事件,而将事件处理委托给外部的处理实体,这种事件处理模型称为授权处理模型。v事件的行为多种多样,由不同的监听器处理。编写事件处理程序首先应确定关注的事件属于何种监听器类型。 v在AWT中,提供11种标准的监听器类型,见下表。 监听器 适配器类 注册方法 ActionListener addActionListenerAdjustmentListener addAdjustmentListenerComponentListener ComponentAdapter addComponentListenerContaine

22、rListener ContainerAdapter addContainerListenerFocusListener FocusAdapter addFocusListenerItemListener addItemListenerKeyListener KeyAdapter addKeyListenerMouseListener MouseAdapter addMouseListenerMouseMotionListener MouseMotionAdapter addMouseMotionListenerTextListener addTextListenerWindowListene

23、r WindowAdapter addWindowListenerv在确定监听器类型后,要用事件源类的注册方法来注册一个监听器类的对象。这样,事件源产生的事件会传送给已注册的处理该类事件的监听器对象,该对象将自动调用相应的事件处理方法来处理该事件。具体的注册方法 是 : 用 监 听 器 类 的 对 象 作 为 参 数 调 用 事 件 源 本 身 的 addXxxListener()方法。该方法的参数是一个监听器类的对象,有多种形式。例如:(1)(1)分分离离的的监监听听器器类类,该该类类通通常常为为继继承承相相应应事事件件适适配配器器类类的的子子类,类中包含了事件处理方法。参数是该类的一个对象

24、。类,类中包含了事件处理方法。参数是该类的一个对象。(2)(2)实实现现监监听听器器接接口口,参参数数为为thisthis,表表示示本本对对象象就就是是一一个个监监听听器类的对象。在本类中包含事件处理方法。器类的对象。在本类中包含事件处理方法。(3)(3)有有名名内内部部类类,参参数数形形式式为为继继承承事事件件适适配配器器类类的的子子类类对对象象,在子类中包含事件处理方法。在子类中包含事件处理方法。(4)(4)匿匿名名内内部部类类,参参数数形形式式为为用用newnew开开始始的的一一个个无无名名的的类类定定义义。其中包含事件处理方法。其中包含事件处理方法。9.2布局管理器v在容器中所有组件的

25、布局(位置和大小)由布局管理器来 控 制 。 在 Java语 言 中 提 供 了 FlowLayout、BorderLayout、GridLayout、CardLayout和GridBagLayout等多种布局管理器。v每种容器都有自己缺省的布局管理器。缺省地,JPanel使用FlowLayout,而内容窗格 ContentPanev(JApplet、 JDialog和 JFrame对 象 的 主 容 器 ) 使 用BorderLayout。如果不希望使用缺省的布局管理器,则可使用所有容器的父类Container的setLayout()方法来改变缺省的布局管理器。 v1.FlowLayoutv

26、FlowLayout布局是一种最基本的布局。这种布局指的是把组件一个接一个从左至右、从上至下地依次放在容器上,每一行中的组件缺省为居中对齐。当容器的尺寸改变后,组件的大小不变,但布局将会随之变化。vFlowLayout是Applet和JPanel的缺省布局管理器。FlowLayout类的构造方法如下:FlowLayoutFlowLayout() () 创创建建每每行行组组件件对对齐齐方方式式为为居居中中对对齐齐、组组件件间间距为距为5 5个像素单位的对象个像素单位的对象FlowLayout(intFlowLayout(int align) align) 创创建建指指定定每每行行组组件件对对齐齐

27、方方式式、组组件件间间距距为为5 5个个像像素素单单位位的的对对象象,alignalign可可取取三三个个静静态态常常量量LEFTLEFT、CENTERCENTER和和RIGHTRIGHT之一(分别表示左、中、右对齐方式)之一(分别表示左、中、右对齐方式)。FlowLayout(intFlowLayout(int align, align, intint hgaphgap, , intint vgapvgap) ) 创创建建指指定定每每行行组组件件对对齐齐方方式式的的对对象象,该该对对象象也也使使用用参参数数vgapvgap和和hgaphgap指指定定了组件间的以像素为单位的纵横间距。了组件间

28、的以像素为单位的纵横间距。v向使用FlowLayout布局的容器添加组件可简单地使用下面的语句: add(add(组件名组件名););v2BorderLayoutvBorderLayout 是内容窗格的缺省布局管理器。内容窗格是框架JFrame,小程序JApplet和对话框JDialog的主容器。BorderLayout将容器的布局分为五个区:北区、南区、东区、西区和中区。这几个区的分布规律是“上北下南,左西右东”。当容器的大小改变时,容器中的各个组件相对位置不变,其中间部分组件的尺寸会发生变化,四周组件宽度固定不变。vBorderLayout类的构造方法如下:BorderLayoutBord

29、erLayout() () 创建组件间无间距的创建组件间无间距的BorderLayoutBorderLayout对象。对象。BorderLayout(intBorderLayout(int hgaphgap, , intint vgapvgap) ) 创创建建有有指指定定组组件件间间距的对象。距的对象。v向BorderLayout布局的容器添加组件时,每添加一个组件都应指明该组件加在哪个区域中。add()方法的第二个参数指明加入的区域,区域东南西北中可用 五 个 静 态 常 量 表 示 : BorderLayout.EAST、BorderLayout.SOUTH、BorderLayout.WE

30、ST、BorderLayout.NORTH和BorderLayout.CENTER。v【例9.3】将五个按钮加入BorderLayout的五个区。import import java.awtjava.awt.*;.*;import import javax.swingjavax.swing.*;.*;public class public class BorderLayoutDemoBorderLayoutDemo extends extends JAppletJApplet public void init() public void init() Container c = Contain

31、er c = getContentPanegetContentPane();(); c.add(new Button( c.add(new Button(北北North), North), BorderLayout.NORTHBorderLayout.NORTH);); c.add(new Button( c.add(new Button(南南South), South), BorderLayout.SOUTHBorderLayout.SOUTH);); c.add(new Button( c.add(new Button(东东East), East), BorderLayout.EASTBo

32、rderLayout.EAST);); c.add(new Button( c.add(new Button(西西West), West), BorderLayout.WESTBorderLayout.WEST);); c.add(new c.add(new Button(Button(中中Center), Center), BorderLayout.CENTERBorderLayout.CENTER);); v程序运行的结果见下图。v3GridLayoutvGridLayout布局是将容器的空间分成若干行和列的一个个网格,可以给出网格的行数和列数,组件添加到这些网格中。当改变容器的大小后,其

33、中的组件相对位置不变,但大小改变。容器中各个组件同高度、同宽度。各个组件缺省的排列方式为:从上到下,从左到右。vGridLayout类的构造方法如下:public public GridLayoutGridLayout()()创创建建单单行行每每个个组组件件一一列列的的GridLayoutGridLayout对对象。象。public public GridLayout(intGridLayout(int rows, rows, intint cols) cols) 创创建建指指定定行行列列数数的的GridLayoutGridLayout对象。对象。public public GridLayou

34、t(intGridLayout(int rows, rows, intint cols, cols, intint hgaphgap, , intint vgapvgap) )创建指定行列数的创建指定行列数的GridLayoutGridLayout对象。对象。v因 为 没 有 容 器 缺 省 使 用 GridLayout, 因 此 在 使 用GridLayout前,要用setLayout()方法将容器的布局管理器设置为GridLayout。v在向GridLayout添加组件时,组件加入容器要按序进行,每个网格中都必须加入组件,若希望某个网格为空,可以为该网格加入一个空的标签:add(new J

35、Label()。v【例9.4】GridLayout布局。import import java.awtjava.awt.*;.*;import import javax.swingjavax.swing.*;.*;public class public class GridLayoutDemoGridLayoutDemo extends extends JAppletJApplet public void init() public void init() Container c = Container c = getContentPanegetContentPane();(); c.setLa

36、yout(newc.setLayout(new GridLayout(3,2); GridLayout(3,2); c.add(new Button(1); c.add(new Button(1); c.add(new Button(2); c.add(new Button(2); c.add(new Button(3); c.add(new Button(3); c.add(new Button(4); c.add(new Button(4); c.add(new Button(5); c.add(new Button(5); c.add(new Button(6); c.add(new B

37、utton(6); v 4.CardLayoutvCardLayout布局管理器能够使得多个组件共享同一显示空间,这些组件之间的关系像一叠重叠的扑克牌,只有最上面的组件是可见的。注意:在一个显示空间(卡片)中只能显示一个组件,因此,可使用容器嵌套的方法来显示多个组件。v 例9.4运行的结果如下图所示。v CardLayout类的构造方法如下:CardLayoutCardLayout()()创建间距为零的对象。创建间距为零的对象。CardLayout(intCardLayout(int hgaphgap, , intint vgapvgap) )创创建建带带有有水水平平hgaphgap和和垂直垂

38、直vgapvgap间距的对象。间距的对象。v为了使用叠在下面的组件,可以为每个组件取一名字,名字在用add()方法向容器添加组件时指定,需要某个组件时通过show()方法指定该组件的名字来选取它。也可以顺序使用这些组件,或直接指明选取第一个组件(用first()方法)或最后一个组件(用last()方法)。v【例9.5】CardLayout布局。import import java.awtjava.awt.*;.*;import import javax.swingjavax.swing.*;.*;public class public class CardLayoutDemoCardLayou

39、tDemo extends extends JAppletJApplet CardLayoutCardLayout clcl =new CardLayout(20,40); =new CardLayout(20,40); / / 组件在卡片中有边界 JButtonJButton b1=new b1=new JButtonJButton(卡片一);); JButtonJButton b2=new b2=new JButtonJButton(卡片二);); JButtonJButton b3=new b3=new JButtonJButton(卡片三);); public void init()

40、public void init() getContentPane().setLayout(clgetContentPane().setLayout(cl);); getContentPane().add(card1,b1); getContentPane().add(card1,b1); getContentPane().add(card2,b2); getContentPane().add(card2,b2); getContentPane().add(card3,b3); getContentPane().add(card3,b3); v程序运行结果如下图所示。程序中的三个按钮组件顺序添

41、加到卡片布局管理器的各个卡片上,它们共享同一显示区域,因此只能见到最上面的“卡片一”按钮。v5.GridBagLayoutvGridBagLayout是最复杂也最灵活的布局管理器。这个布局管理器将组件放入单元格中,但允许一些组件跨越单元格。v可用GridBagLayout类的构造方法GridBagLayout()来创建一个GridBagLayout布局管理器。因GridBagLayout布局设置比较复杂,这里就不介绍了,请读者参看API说明或其他资料。 v6.自定义布局v若希望按照自己的要求来进行组件和界面图形元素的布局,可用容器的setLayout(null)方法将容器的布局管理器设置为空,

42、然后用下面的方法设置组件在容器中的位置和大小:setBounds(intsetBounds(int a,inta,int b,intb,int width,intwidth,int height) height)v其中,参数a和b指定矩形形状的组件左上角在容器中的坐标,width和height指定组件的宽和高。v【例9.6】设置自己的布局管理器。import import java.awtjava.awt.*;.*;import import javax.swingjavax.swing.*;.*;class class NullLayoutNullLayout extends extends

43、 JFrameJFrame NullLayoutNullLayout()() super( super(建设自己的布局管理器);); Container c= Container c=getContentPanegetContentPane();(); / / 也可不用内容窗格 c.setLayout(nullc.setLayout(null););JButtonjb1=newJButton(按钮1);JButtonjb2=newJButton(按钮2);c.add(jb1);c.add(jb2);jb1.setBounds(10,10,100,30);jb2.setBounds(10,50,

44、100,30);publicstaticvoidmain(Stringargs)NullLayoutnl=newNullLayout();nl.setSize(200,150);nl.setVisible(true);v程序的运行结果如下图所示。注意,采用这种方式的布局,组件的位置和大小将不随窗口大小的变化而变化。下图为例9.6的运行界面。9.3常用Swing组件v9.3.1 容器组件v1.JFrame框架v框架,是JFrame类的对象,是swing GUI应用程序的主窗口。窗口有边界、标题、关闭按钮等。对Java应用程序,应至少包含一个框架,例9.1的应用程序即使用了框架。有时,小程序也使用

45、框架。JFrame类继承于Frame类。JFrame类的构造方法如下:JFrameJFrame() () 创建无标题的初始不可见框架。创建无标题的初始不可见框架。JFrame(StringJFrame(String title) title) 创创建建标标题题为为titletitle的的初初始始不不可可见见框框架。架。 v例如,创建带标题“Java GUI应用程序”的框架对象frame,可用语句:JFrameJFrame frame = new frame = new JFrame(JavaJFrame(Java GUI GUI应用程序);v 要显示框架对象代表的框架窗口,可使用方法setVi

46、sible()。可用语句: frame.setVisible(trueframe.setVisible(true););v可使得JFrame类对象frame表示的框架窗口显示到屏幕上。一般在显示框架前,可设置框架的初始显示大小可使用setSize()方法或pack()方法。例如: frame.setSize(200,150);frame.setSize(200,150); / / 设置框架窗口初始大小为200200150150点 frame.pack(); frame.pack(); / / 设置框架窗口初始大小为刚好只显示出所有的组件。v在向框架添加组件时,并不直接添加组件到框架,而是添加到

47、内容窗格(content pane),改变其他特性(布局管理器、背景色等)也对内容窗格进行。要存取内容窗格,可通过getContentPane()方法, 若希望用自己的容器替换掉内容窗格(例如用JPanel),可以使用setContentPane()方法。 v选择框架的关闭按钮后,框架窗口将自动关闭,但若是应用单个框架的应用程序,为了在选择框架的关闭按钮时能退出程序,应添加WindowListener监听器或书写下列代码:frame.setDefaultCloseOperationframe.setDefaultCloseOperation( ( JFrame.EXIT_ON_CLOSEJFr

48、ame.EXIT_ON_CLOSE); ); vJFrame的缺省观感为Java (Metal), 若要使用其他的观感,必须显式设置。JFrame(应该说是内容窗格)的缺省布局管理器是BorderLayout。v2. JPanel面板vJPanel是一种添加到其他容器使用的容器组件,可将组件添加到JPanel,然后再将JPanel添加到某个容器。JPanel也提供一个绘画区域,可代替AWT的画布Canvas (没有JCanvas)。vjavax.swing.JPanel类继承于javax.swing.JComponent类,其构造方法有:public public JPanelJPanel()

49、 () 创建具有缺省FlowLayoutFlowLayout布局的JPanelJPanel对象。public public JPanel(LayoutManagerJPanel(LayoutManager layout) layout) 创建具有指定布局管理器的JPanelJPanel对象。v将JPanel作为画布的绘画区域使用时,要使用下面的两个步骤:首先,设置画布绘图区域的大小;其次,使用paintComponent()方法(不是paint()方法)来绘图,在该方法体中,首先调用方法super.paintComponent()来清除显示区域。 v例如: publicvoidpaintCom

50、ponent(Graphicsg)super.paintComponent(g);.vJPanel可指定边界,可用的边界有titled、etched、beveled 、line、matte、compound和empty等,也可以创建自己的边界。可用JComponent类的setBorder()方法设置边界。其用法如下: publicvoidsetBorder(Borderborder)v其中,Border类的参数可用javax.swing.BorderFactory类中的方法获得。获取各种相应边界的方法为:createTitledBorder()createEtchedBorder()crea

51、teBevelBorder()createRaisedBevelBorder()createLoweredBevelBordercreateLoweredBevelBorder() () createLineBordercreateLineBorder()()createMatteBordercreateMatteBorder() () createCompoundBordercreateCompoundBorder()()createEmptyBordercreateEmptyBorder()()v【例9.7】使用JPanel。import import java.awtjava.awt.*

52、;.*;import import javax.swingjavax.swing.*;.*;class class JPanelDemoJPanelDemo extends extends JPanelJPanel JButtonJButton b1 = new b1 = new JButton(JPanelJButton(JPanel);); JButtonJButton b2 = new b2 = new JButton(DemoJButton(Demo);); public public JPanelDemoJPanelDemo() () setBackground(Color.whit

53、esetBackground(Color.white);); add(b1); add(b1); add(b2); add(b2); public static void main(String public static void main(String argsargs) ) JPanelJPanel jpjp = new = new JPanelDemoJPanelDemo();(); jp.setBorderjp.setBorder( ( BorderFactory.createTitledBorderBorderFactory.createTitledBorder( ( Hello,

54、Border); Hello,Border); JFrameJFrame frame = new frame = new JFrame(JPanelDemoJFrame(JPanelDemo);); frame.setSize(200, 150); frame.setSize(200, 150); frame.setContentPane(jpframe.setContentPane(jp);); frame.setDefaultCloseOperationframe.setDefaultCloseOperation( ( JFrame.EXIT_ON_CLOSEJFrame.EXIT_ON_

55、CLOSE);); frame.setVisible(trueframe.setVisible(true);); v例9.7程序运行结果如下图所示。v3.JAppletvjavax.swing.JApplet类是java.applet.Applet类的子类。使用Swing组件的小程序需继承JApplet类。v 除了所处的java包不同外,JApplet与Applet的主要区别还有:v(1)缺省的布局管理器不同v Applet缺省的布局管理器是FlowLayout,而JApplet(内容窗格)缺省的布局管理器是BorderLayout。v(2)加入组件的方式不同vApplet可直接加入组件,而J

56、Applet缺省使用内容窗格ContentPane作为主容器。加入Swing组件时,要先使用JApplet的方法getContentPane()获得一个Container对象,再调用这个对象的add()方法将Swing组件加入到JApplet的容器中。v4.JTabbedPanevjavax. javax.swing.JTabbedPane类继承于javax.swing.JComponent,它的对象反映为一组带标签的面板,每个面板都可以存放组件,因此JTabbedPane是一容器组件。vJTabbedPane类的构造方法有:JTabbedPaneJTabbedPane()()创建空对象,该对

57、象具有缺省的标签位置创建空对象,该对象具有缺省的标签位置JTabbedPane.TOPJTabbedPane.TOP和缺省的布局策略和缺省的布局策略JTabbedPane.WRAP_TAB_LAYOUTJTabbedPane.WRAP_TAB_LAYOUT。JTabbedPane(intJTabbedPane(int tabPlacementtabPlacement) )创建空对象,该对象具有创建空对象,该对象具有指定的标签位置:指定的标签位置:JTabbedPane.TOPJTabbedPane.TOP、JTabbedPane.BOTTOMJTabbedPane.BOTTOM、JTabbed

58、Pane.LEFTJTabbedPane.LEFT或或JTabbedPane.RIGHTJTabbedPane.RIGHT以及缺省的布局策以及缺省的布局策略略JTabbedPane.WRAP_TAB_LAYOUTJTabbedPane.WRAP_TAB_LAYOUT。JTabbedPane(intJTabbedPane(int tabPlacementtabPlacement, , intint tabLayoutPolicytabLayoutPolicy) )创建空对象,该对象具有指定的标签位置和布局策略。创建空对象,该对象具有指定的标签位置和布局策略。v【例9.8】使用JTabbedPan

59、e容器。import import java.awtjava.awt.*;.*;import import java.awt.eventjava.awt.event.*;.*;import import javax.swingjavax.swing.*;.*;import import javax.swing.eventjavax.swing.event.*;.*;public class public class JTabbedPaneDemoJTabbedPaneDemo public static void main(String public static void main(Stri

60、ng argsargs) new new MyTabbedPaneMyTabbedPane();(); class class MyTabbedPaneMyTabbedPane extends extends JFrameJFrame implements implements ChangeListener,ActionListenerChangeListener,ActionListener JTabbedPaneJTabbedPane jtjt; ; JButtonJButton jbjb; intint index = 0; index = 0;MyTabbedPaneMyTabbedP

61、ane()() super( super(使用标签面板容器);); jtjt = new = new JTabbedPaneJTabbedPane();(); jbjb = new JButton5; = new JButton5; for(intfor(int i = 0;i5;i+) i = 0;i5;i+) jbijbi = new = new JButtonJButton(第 + + i + i + 页面板);); jbi.addActionListener(thisjbi.addActionListener(this);); jt.addTabjt.addTab(页标签 + + i,

62、jbii,jbi);); jt.addChangeListener(thisjt.addChangeListener(this);); getContentPane().add(jt,BorderLayout.CENTERgetContentPane().add(jt,BorderLayout.CENTER);); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSEsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ); setSize(300,200); setSize(300,200); setVisibl

63、e(truesetVisible(true);); public void public void stateChanged(ChangeEventstateChanged(ChangeEvent e) e) if(e.getSourceif(e.getSource()=()=jtjt) intint i = ( i = (JTabbedPane)e.getSourceJTabbedPane)e.getSource()() . .getSelectedIndexgetSelectedIndex();(); jbindex.setVisible(falsejbindex.setVisible(f

64、alse);); jbi.setVisible(truejbi.setVisible(true);); index = i; index = i; public void public void actionPerformed(ActionEventactionPerformed(ActionEvent e) e) setTitlesetTitle( (“响应单击” +( +(JButton)e.getSource().getTextJButton)e.getSource().getText();(); v例9.8运行结果如下图所示。v9.3.2 按钮(JButton)v按钮是GUI中非常重要

65、的一种基本组件。按钮一般对应一个事先定义好的事件、执行功能、一段程序。当使用者单击按钮时,系统自动执行与该按钮联系的程序,从而完成预定的功能。vJButton类提供对按钮的支持,它的类层次关系如下: java.awt.Containerjava.awt.Container javax.swing.JComponentjavax.swing.JComponent javax.swing.AbstractButtonjavax.swing.AbstractButton javax.swing.JButtonjavax.swing.JButton vJButton类有如下的构造方法:JButtonJ

66、Button() () 创建空按钮。创建空按钮。JButton(IconJButton(Icon icon) icon) 创建带图标的按钮。创建带图标的按钮。JButton(StringJButton(String text) text) 创建带文字的按钮。创建带文字的按钮。JButton(StringJButton(String text, text, Icon Icon icon) icon) 创创建建带带文文字字和和图图标标的的按按钮。钮。vJButton组件与AWT的Button组件相比,增加了显示文本中可用HTML标记,可带图标等功能。v在 JButton按 钮 的 使 用 中 ,

67、常 用 到 继 承 来 的setMnemonic()(设置快捷字母键)、setActionCommand()(设置动作命令)方法等。vJButton组 件 引 发 的 事 件 为 ActionEvent, 可 实 现ActionListener监听器接口的actionPerformed()方法,用addActionListener()方法注册,用getActionCommand()或getSource()方法确定事件源。v【例9.9】设计一个GUI应用程序,有两个标签l1、l2和三个按钮b1,b2,b3。l1标签显示固定的文字,l2标签的文字随选择不同的按钮而变化;选择b1按钮时,l2标签显示

68、为“欢迎进入Java世界”,选择b2按钮时,l2标签显示当前的日期,选择b3按钮时,退出该应用程序。程序如下:import import java.awtjava.awt.*;.*;import import java.awt.eventjava.awt.event.*;.*;import import javax.swingjavax.swing.*;.*;import java.util.*;import java.util.*;public class public class JButtonDemoJButtonDemo extends extends JpanelJpanel imp

69、lements implements ActionListenerActionListener JButtonJButton b1,b2,b3; b1,b2,b3; static static JLabelJLabel l1,l2; l1,l2; JButtonDemoJButtonDemo()()l1 = new l1 = new JLabelJLabel( ( 这是一个演示按钮动作的程序,JLabel.CENTERJLabel.CENTER);); l2 = new l2 = new JLabelJLabel( ,( ,JLabel.CENTERJLabel.CENTER);); b1 =

70、 new b1 = new JButtonJButton(欢迎 w);w); b1.setMnemonic(KeyEvent.VK_W);/ b1.setMnemonic(KeyEvent.VK_W);/ 设置按钮的快捷键 b1.setActionCommand(welcome); b1.setActionCommand(welcome); b2 = new b2 = new JButtonJButton(日期 d);d); b2.setMnemonic(KeyEvent.VK_D);/ b2.setMnemonic(KeyEvent.VK_D);/ 设置快捷字符为D D b2.setActi

71、onCommand(date); b2.setActionCommand(date); b3 = new b3 = new JButtonJButton(退出 q);q); b3.setMnemonic(KeyEvent.VK_Q);/ b3.setMnemonic(KeyEvent.VK_Q);/ 设置快捷字符为Q Q b3.setActionCommand(quit); b3.setActionCommand(quit); b1.addActionListener(this); b1.addActionListener(this); b2.addActionListener(this);

72、b2.addActionListener(this); b3.addActionListener(this); b3.addActionListener(this);add(b1);add(b2);add(b3);add(b1);add(b2);add(b3); public void public void actionPerformed(ActionEventactionPerformed(ActionEvent e) e) Calendar c1 = Calendar c1 = Calendar.getInstanceCalendar.getInstance();(); if(e.get

73、ActionCommand().equals(welcomeif(e.getActionCommand().equals(welcome) l2.setText( l2.setText(欢迎进入JavaJava世界。);); else else if(e.getActionCommand().equals(dateif(e.getActionCommand().equals(date) l2.setText( l2.setText(今天是+c1.get(Calendar.YEAR)+c1.get(Calendar.YEAR)+ 年+(+(c1.get(Calendar.MONTH)+1)+c1

74、.get(Calendar.MONTH)+1)+ 月 + + c1.get(Calendar.DATE) + c1.get(Calendar.DATE) + 日);); else System.exit(0); else System.exit(0); l2.setHorizontalAlignment(JLabel.CENTER); l2.setHorizontalAlignment(JLabel.CENTER); / / 标签文字水平居中 public static void main(String public static void main(String argsargs) JFra

75、meJFrame frame=new frame=new JFrameJFrame(使用JButtonJButton);); frame.getContentPane().add(newframe.getContentPane().add(new JButtonDemo(),BorderLayout.SOUTHJButtonDemo(),BorderLayout.SOUTH);); frame.getContentPane().add(l1,BorderLayout.NORTHframe.getContentPane().add(l1,BorderLayout.NORTH);); frame.

76、getContentPane().add(l2,BorderLayout.CENTEframe.getContentPane().add(l2,BorderLayout.CENTER);R); frame.setDefaultCloseOperationframe.setDefaultCloseOperation( ( JFrame.EXIT_ON_CLOSEJFrame.EXIT_ON_CLOSE);); frame.pack(); frame.pack(); frame.setVisible(trueframe.setVisible(true);); v本程序中命令按钮设置了快捷字母键,可

77、用鼠标单击或按Alt + 快捷字母来选择按钮。v例9.9运行启动后选择 “欢迎” 按钮和选择“日期”按钮后显示的情况见下左图和下右图。v【例9.10】带图形和HTML文字的按钮。import import java.awtjava.awt.*;.*;import import javax.swingjavax.swing.*;.*;public class JButtonDemo1 extends public class JButtonDemo1 extends JFrameJFrame public static void public static void main(Stringmai

78、n(String argsargs) new JButtonDemo1( ); new JButtonDemo1( ); public JButtonDemo1( )public JButtonDemo1( ) super(Usingsuper(Using JButtonJButton);); Container content = Container content = getContentPanegetContentPane();(); content.setBackground(Color.whitecontent.setBackground(Color.white);); conten

79、t.setLayout(newcontent.setLayout(new FlowLayoutFlowLayout();(); JButtonJButton button1 = new button1 = new JButtonJButton( ( Java); Java); content.add(button1); content.add(button1); ImageIconImageIcon imim = new = new ImageIconImageIcon( ( images/ images/newssms.gifnewssms.gif);); JButtonJButton bu

80、tton2 = new button2 = new JButton(imJButton(im); ); content.add(button2);content.add(button2); JButtonJButton button3 = new button3 = new JButton(JavaJButton(Java, , imim);); content.add(button3); content.add(button3); JButtonJButton button4 = new button4 = new JButton(JavaJButton(Java, , imim);); b

81、utton4.setHorizontalTextPosition( button4.setHorizontalTextPosition( SwingConstants.LEFTSwingConstants.LEFT);); content.add(button4); content.add(button4); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSEsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);); pack(); pack(); setVisible(truesetVisible(true);)

82、; v程序中使用了类IconImage和指定图标图像文件名来创建图标图像对象,程序的运行结果如下图所示。v9.3.3 标签(JLabel)v标签是用户不能修改只能查看其内容的组件,常用来在界面上输出信息。JLabel类提供了对标签的支持,它的类层次关系为:javax.swing.JComponent - javax.swing.JLabel。vJLabel类的构造方法有:JLabelJLabel() () 创建一个空标签。JLabel(IconJLabel(Icon image) image) 创建一个带指定图像的标签。JLabel(IconJLabel(Icon image, image,

83、intint horizontalAlignmenthorizontalAlignment) )创建一个带指定图像和水平对齐方式的标签。JLabel(StringJLabel(String text) text) 创建一个带文字的标签。JLabel(StringJLabel(String text, text, Icon Icon icon, icon, intint horizontalAlignmenthorizontalAlignment) )创建一个带文字、图像和指定水平对齐方式的标签。 JLabel(String text, int horizontalAlignment)创建一个带

84、文字和指定水平对齐方式的标签。v其中,horizontalAlignment水平对齐方式可以使用表示左对齐、右对齐、居中对齐的常量JLabel.LEFT、JLabel.LEFT和JLabel.CENTER。v【例9.11】具有文字对齐的标签。import javax.swing.*;import java.awt.*;public class JLabelAlignDemo extends JApplet public void init() Container c = getContentPane(); c.add(new JLabel(文字左对齐标签,JLabel.LEFT), Borde

85、rLayout.NORTH); c.add(new JLabel(文字右对齐标签,JLabel.RIGHT), BorderLayout.CENTER); c.add(newc.add(new JLabelJLabel(文字居中标签,JLabel.CENTERJLabel.CENTER),), BorderLayout.SOUTHBorderLayout.SOUTH);); v程序运行结果见下图。vJLabel类常用方法有:public public void void setText(StringsetText(String text)text)定义这个组件将显示的单行文字。public S

86、tring public String getTextgetText() () 返回标签显示的文字。public Icon public Icon getIcongetIcon() () 返回标签显示的图像。public public void void setIcon(IconsetIcon(Icon icon)icon)定义这个组件将显示的图标。v【例9.12】使用带图标的标签。import import javax.swingjavax.swing.*;.*;import import java.awtjava.awt.*; .*; import import java.awt.even

87、tjava.awt.event.*; .*; public class public class JLabelDemoJLabelDemo extends extends JAppletJApplet public void init() public void init() Container c = Container c = getContentPanegetContentPane(); (); Icon icon = new Icon icon = new ImageIcon(images/cup.gifImageIcon(images/cup.gif);); JLabelJLabel

88、 label = new label = new JLabelJLabel( ( Swing!, icon, Swing!, icon, JLabel.CENTERJLabel.CENTER); ); c.add(labelc.add(label, , BorderLayout.CENTERBorderLayout.CENTER); ); v程序运行结果如下图所示。v9.3.4 复选框(JCheckBox)vJCheckBox类提供复选框按钮的支持。复选框按钮是具有开关或真假状态的按钮。JCheckBox类的层次关系为: javax.swing.AbstractButtonjavax.swin

89、g.AbstractButton javax.swing.JToggleButtonjavax.swing.JToggleButton javax.swing.JCheckBoxjavax.swing.JCheckBoxvJCheckBox类的构造方法如下:JCheckBoxJCheckBox()()创建无文本的初始未选复选框按钮。JCheckBox(IconJCheckBox(Icon icon)icon)创建有图像无文本的初始未选复选框按钮。JCheckBox(IconJCheckBox(Icon icon, icon, booleanboolean selected)selected)创

90、建带图像和选择状态但无文本的复选框按钮。 JCheckBox(StringJCheckBox(String text)text)创建带文本的初始未选复选框按钮。JCheckBox(StringJCheckBox(String text, text, booleanboolean selected)selected)创建具有指定文本和状态的复选框按钮。JCheckBox(StringJCheckBox(String text, text, Icon Icon icon)icon)创建具有指定文本和图标图像的初始未选复选框按钮。JCheckBox(StringJCheckBox(String te

91、xt, text, Icon Icon icon, icon, booleanboolean selected)selected)创建具有指定文本、图标图像、选择状态的复选框按钮。v其中,构造方法的参数selected若为真,则表示按钮初始状态为选中。vJCheckBox类常用的方法有继承来的方法isSelected(),其格式为:public public booleanboolean isSelectedisSelected()()当复选框按钮选中时返回truetrue,否则返回falsefalse。vJCheckBox类 的 选 择 事 件 是 ItemEvent , 可 实 现Item

92、Listener监听器接口的itemStateChanged()方法来处理事件,用addItemListener()方法注册。v【例9.13】选择粗体、斜体复选框按钮,改变文本框中显示文字的字形。import import javax.swingjavax.swing.*;.*;import import java.awt.eventjava.awt.event.*;.*;import import java.awtjava.awt.*;.*;public class public class JCheckBoxDemoJCheckBoxDemo extends extends Japplet

93、Japplet implements implements ItemListenerItemListener private private JTextFieldJTextField t; t; private private JCheckBoxJCheckBox bold,italic; bold,italic; public void init() public void init() t = new t = new JTextFieldJTextField(观察这里文字字形的变化,40);,40);t.setFont(newt.setFont(new Font(Serif,Font.PL

94、AIN,20); Font(Serif,Font.PLAIN,20); getContentPane().add(t,BorderLayout.NORTHgetContentPane().add(t,BorderLayout.NORTH);); bold = new bold = new JCheckBoxJCheckBox(粗体Bold);Bold); bold.addItemListener(thisbold.addItemListener(this);); getContentPane().add(bold,BorderLayout.CENTERgetContentPane().add(

95、bold,BorderLayout.CENTER);); italic = new italic = new JCheckBoxJCheckBox(斜体Italic);Italic); italic.addItemListener(thisitalic.addItemListener(this);); getContentPane().add(italic,BorderLayout.SOUTHgetContentPane().add(italic,BorderLayout.SOUTH);); public void public void itemStateChanged(ItemEventi

96、temStateChanged(ItemEvent e) e) intint b = b = bold.isSelected()?Font.BOLD:Font.PLAINbold.isSelected()?Font.BOLD:Font.PLAIN; ; intint i = i = italic.isSelected()?Font.ITALIC:Font.PLAINitalic.isSelected()?Font.ITALIC:Font.PLAIN; ; t.setFont(newt.setFont(new Font(Serif,b + i,20); Font(Serif,b + i,20);

97、 v程序运行结果如下图所示。v9.3.5 单选按钮(JRadioButton)v在一组单选按钮中,可进行选择其中一个的操作,即进行“多选一”。JRadioButton类的类层次和构造方法的参数构成都与前面介绍的JCheckBox类相同。这里不再列出JRadioButton类的这些内容。v因为单选按钮是在一组按钮中选择一个,因此,必须将单选按钮分组,即指明在一个组中包含哪些按钮。可用ButtonGroup创建按钮组对象,应用对象的add()方法顺序加入各个单选按钮。v在单选按钮中也可以使用HTML代码。这是Java SDK 1.3版新增的功能。v单选按钮的选择事件是ActionEvent类事件。

98、v【例9.14】使用单选按钮来设置Swing应用程序的不同观感。import import java.awtjava.awt.*;.*;import import java.awt.eventjava.awt.event.*;.*;import import javax.swingjavax.swing.*;.*;public class public class JRadioButtonDemoJRadioButtonDemo extends extends JPanelJPanel static static JFrameJFrame frame; frame; static String

99、 metal= Metal; static String metal= Metal; static String motif = Motif; static String motif = Motif; static String windows = Windows; static String windows = Windows; JRadioButtonJRadioButton metalButtonmetalButton, , motifButton,windowsButtonmotifButton,windowsButton; ; public public JRadioButtonDe

100、moJRadioButtonDemo()() JButtonJButton button = new button = new JButton(HelloJButton(Hello, world);, world); button.setMnemonic(hbutton.setMnemonic(h);); metalButtonmetalButton = new = new JRadioButton(metalJRadioButton(metal);); metalButton.setMnemonic(ometalButton.setMnemonic(o); ); metalButton.se

101、tActionCommand(metalmetalButton.setActionCommand(metal););motifButtonmotifButton = new = new JRadioButton(motifJRadioButton(motif););motifButton.setMnemonic(mmotifButton.setMnemonic(m); ); motifButton.setActionCommand(motifmotifButton.setActionCommand(motif););windowsButtonwindowsButton = new = new

102、JRadioButton(windowsJRadioButton(windows););windowsButton.setMnemonic(wwindowsButton.setMnemonic(w); ); windowsButton.setActionCommand(windowswindowsButton.setActionCommand(windows););/ / 将单选按钮设置为一组ButtonGroupButtonGroup group = new group = new ButtonGroupButtonGroup();();group.add(metalButtongroup.

103、add(metalButton););group.add(motifButtongroup.add(motifButton););group.add(windowsButtongroup.add(windowsButton););/ / 对单选按钮设置监听器RadioListenerRadioListener myListenermyListener = new = new RadioListenerRadioListener();();metalButton.addActionListener(myListenermetalButton.addActionListener(myListene

104、r););motifButton.addActionListener(myListenermotifButton.addActionListener(myListener););windowsButton.addActionListener(myListenerwindowsButton.addActionListener(myListener);); add(buttonadd(button);); add(metalButtonadd(metalButton);); add(motifButtonadd(motifButton); ); add(windowsButtonadd(windo

105、wsButton);); /* /* ActionListenerActionListener监听器监听单选按钮*/*/class class RadioListenerRadioListener implements implements ActionListenerActionListener / / 嵌套类 public void public void actionPerformed(ActionEventactionPerformed(ActionEvent e) e) if(e.getActionCommand().equals(metalif(e.getActionCommand

106、().equals(metal) SetLAF.setJavaLookAndFeelSetLAF.setJavaLookAndFeel();(); else else if(e.getActionCommand().equals(motifif(e.getActionCommand().equals(motif) SetLAF.setMotifLookAndFeelSetLAF.setMotifLookAndFeel();(); else else SetLAF.setNativeLookAndFeelSetLAF.setNativeLookAndFeel();(); SwingUtiliti

107、es.updateComponentTreeUI(frameSwingUtilities.updateComponentTreeUI(frame););frame.pack();frame.pack(); public static void main(String s) public static void main(String s) JRadioButtonDemoJRadioButtonDemo panel = new panel = new JRadioButtonDemoJRadioButtonDemo();(); frame = new frame = new JFrameJFr

108、ame(使用JRadioButtonJRadioButton选择观感);); frame.setDefaultCloseOperationframe.setDefaultCloseOperation( ( JFrame.EXIT_ON_CLOSEJFrame.EXIT_ON_CLOSE);); frame.getContentPane().add(Centerframe.getContentPane().add(Center, panel);, panel); frame.pack(); frame.pack(); frame.setVisible(trueframe.setVisible(t

109、rue);); v程序运行时可用单选按钮选择三种不同的观感,运行结果如下图上、中和下所示。 v例9.14程序运行时选择不同单选按钮的界面。v9.3.6 文 本 框 ( JTextField、 JPassWord和JTextArea)vJava语言提供了单行文本框、口令框和多行文本框等文本框形式,它们都是人机交互的主要组件。v1单行文本框(JTextField)v单行文本框一般用来让用户输入如姓名、地址这样的信息,它是一个能够接收用户的键盘输入的单行文本区域。类JTextField提供对单行文本框的支持,它的类层次如下: javax.swing.Jcomponentjavax.swing.Jco

110、mponent javax.swing.text.JTextComponentjavax.swing.text.JTextComponent javax.swing.JTextFieldjavax.swing.JTextFieldvJTextField类有如下的几种构造方法:JTextFieldJTextField( ) ( ) 创建一个新的单行文本框。JTextField(intJTextField(int columns) columns) 创建具有指定长度的空单行文本框。JTextField(StringJTextField(String text) text) 创建带初始文本内容的单行

111、文本框。JTextField(StringJTextField(String text, text, intint columns) columns) 创建带初始文本内容并具有指定长度的单行文本框。vJTextField类的常用方法有:public void public void setText(StringsetText(String s) s)在文本框中显示字符串s s。public String public String getTextgetText()()获得文本框中的字符串。v当用户在文本框里敲“回车”键时,就产生了一个ActionEvent事件。当用户在文本框中移动文本光标时,

112、就产生CaretEvent事件,可注册addCaretListener监听器,实现CaretListener的caretUpdate()进行事件处理。v【例9.15】编写温度变换的应用程序,将摄氏温度转换为华氏温度。 import import java.awtjava.awt.*;.*;import import java.awt.eventjava.awt.event.*;.*;import import javax.swingjavax.swing.*;.*;public class public class CelsiusConverterCelsiusConverter implem

113、ents implements ActionListenerActionListener JFrameJFrame frame; frame; JPanelJPanel panel; panel; JTextFieldJTextField tempCelsiustempCelsius; ; JLabelJLabel celsiusLabelcelsiusLabel, , fahrenheitLabelfahrenheitLabel; ; JButtonJButton convertTempconvertTemp; ; public public CelsiusConverterCelsiusC

114、onverter() / () / 构造方法 frame = new frame = new JFrameJFrame(温度变换);); panel = new panel = new JPanelJPanel();(); panel.setLayout(newpanel.setLayout(new GridLayout(2, 2); GridLayout(2, 2);tempCelsiustempCelsius = new = new JTextFieldJTextField();(); celsiusLabelcelsiusLabel = new = new JLabelJLabel(摄氏

115、温度 = ); = ); convertTempconvertTemp = new = new JButtonJButton(变换);); fahrenheitLabelfahrenheitLabel = new = new JLabelJLabel(?华氏温度);); convertTemp.addActionListener(thisconvertTemp.addActionListener(this); ); panel.add(tempCelsiuspanel.add(tempCelsius);); panel.add(celsiusLabelpanel.add(celsiusLabe

116、l);); panel.add(convertTemppanel.add(convertTemp);); panel.add(fahrenheitLabelpanel.add(fahrenheitLabel);); frame.getContentPane().addframe.getContentPane().add( ( panel,BorderLayout.CENTERpanel,BorderLayout.CENTER);); frame.setDefaultCloseOperationframe.setDefaultCloseOperation( ( JFrame.EXIT_ON_CL

117、OSEJFrame.EXIT_ON_CLOSE);); frame.packframe.pack();/ ();/ 显示变换程序 frame.setVisible(trueframe.setVisible(true);); / / 实现监听器接口 public public void void actionPerformed(ActionEventactionPerformed(ActionEvent event) event) intint tempFtempF; ; tempFtempF = ( = (int)(Double.parseDoubleint)(Double.parseDoub

118、le( ( tempCelsius.getTexttempCelsius.getText() * 1.8 + 32);() * 1.8 + 32); fahrenheitLabel.setText(tempFfahrenheitLabel.setText(tempF + + 华氏温度);); public static void main(String public static void main(String argsargs) ) CelsiusConverterCelsiusConverter converter = converter = new new CelsiusConvert

119、erCelsiusConverter();(); v程序运行显示如下图所示。 v2口令框(JPasswordField)v单行口令文本框JPasswordField类是JTextField类的子类。在JPasswordField对象中输入的文字会被其他字符替代,这个组件常用来在Java程序中输入口令。vJPasswordField类的构造方法与JTextField类的构造方法类似,常用的其他方法有:char char getPasswordgetPassword() () 返回输入的口令。char char getEchoChargetEchoChar() () 返回输入文本时回显在框中的字符

120、。回显字符缺省为字符“* *”。void void setEchoChar(charsetEchoChar(char c) c) 设置回显字符。v【例9.16】使用口令框。import import java.awtjava.awt.*;.*;import import java.awt.eventjava.awt.event.*;.*;import import javax.swingjavax.swing.*;.*;public class public class JPasswordFieldDemoJPasswordFieldDemo extends extends JAppletJA

121、pplet implements implements ActionListenerActionListener JLabelJLabel jl1,jl2; jl1,jl2; JPasswordFieldJPasswordField jp1,jp2; jp1,jp2; JButtonJButton jb1,jb2; jb1,jb2; public void init() public void init() Container c = Container c = getContentPanegetContentPane();(); jl1 = new jl1 = new JLabelJLabe

122、l( ( 请输入您的密码: ,: ,JLabel.CENTERJLabel.CENTER);); jl2 = new jl2 = new JLabelJLabel( ( 请再次输入密码: ,: ,JLabel.CENTERJLabel.CENTER););jp1 = new JPasswordField(8);jp1 = new JPasswordField(8); jp2 = new JPasswordField(8); jp2 = new JPasswordField(8); jb1 = new jb1 = new JButtonJButton(提交);); jb2 = new jb2 =

123、 new JButtonJButton(取消);); c.setLayout(newc.setLayout(new GridLayout(3,2); GridLayout(3,2); c.add(jl1); c.add(jl1); c.add(jp1); c.add(jp1); c.add(jl2); c.add(jl2); c.add(jp2); c.add(jp2); c.add(jb1); c.add(jb1); c.add(jb2); c.add(jb2); jb1.addActionListener(this); jb1.addActionListener(this); jb2.ad

124、dActionListener(this); jb2.addActionListener(this); public void public void actionPerformed(ActionEventactionPerformed(ActionEvent e) e) if(e.getSourceif(e.getSource()=jb1)()=jb1) if(jp1.getPassword().length0) if(jp1.getPassword().length0) if(String.valueOf(jp1.getPassword().equals if(String.valueOf

125、(jp1.getPassword().equals (String.valueOf(jp2.getPassword() (String.valueOf(jp2.getPassword() showStatusshowStatus(密码输入成功!);); else else showStatusshowStatus(两次输入的密码不同,请重新输入!);); jp1.setText(); jp1.setText(); jp2.setText(); jp2.setText(); else else showStatusshowStatus(密码不能为空!);); if(e.getSourceif(e

126、.getSource()=jb2)()=jb2) jp1.setText(); jp1.setText(); jp2.setText(); jp2.setText();showStatusshowStatus();(); v程序运行显示如下图所示。v3多行文本框(JTextArea)vJTextField 是单行文本框,不能显示多行文本,如果想要显示大段的多行文本,可以使用类JTextArea支持的多行文本框。JTextArea 有六个构造方法,常用的有四个:JTextAreaJTextArea() () 创建空多行文本框。JTextArea(intJTextArea(int rows, ro

127、ws, intint columns) columns) 创建指定行列数的多行文本框。JTextArea(StringJTextArea(String text) text) 创建带初始文本内容的多行文本框。JTextArea(StringJTextArea(String text, text, intint rows, rows, intint columns) columns) 创建带初始文本内容和指定大小的多行文本框。v其中,text 为 JTextArea 的初始化文本内容;rows 为 JTextArea 的高度,以行为单位;columns 为 JTextArea 的宽度,以字符为单

128、位。v例如,构造一个高5行,宽15个字符的多行文本框的语句为: textArea = new JTextArea(5, 15);v多行文本框默认是不会自动折行的 (但可以输入回车符 换 行 ), 可 以 使 用 类 JTextArea 的 setLineWrap(boolean wrap)方法设置是否允许自动折行。wrap为true时允许自动折行。多行文本框会根据用户输入的内容自动扩展大小。若不自动折行,那么多行文本框的宽度由最长的一行文字确定的;若数据行数超过了预设的行数,则多行文本框会扩展自身的高度去适应。换句话说,多行文本框不会自动产生滚动条。这时,可用滚动窗格 (JScrollPane

129、) 来为多行文本框增加滚动条。v滚动窗格是一个能够自己产生滚动条的容器,通常只包容一个组件,并且根据这个组件的大小自动产生滚动条。v多行文本框里文本内容的获得和设置,同样可以使用 getText()和 setText() 两 个 方 法 来 完 成 。 还 可 以 用setEditable(boolean) 确定是否可对多行文本框的内容进行编辑。v【例9.17】使用带滚动条的多行文本框。import import javax.swingjavax.swing.*;.*;import import java.awtjava.awt.*;.*;public class public class J

130、TAreaAndJSPaneDemoJTAreaAndJSPaneDemo extends extends JFrameJFrame public public JTAreaAndJSPaneDemoJTAreaAndJSPaneDemo() () super( super(使用带滚动条的多行文本框);); JTextAreaJTextArea textAreatextArea = new JTextArea(5, 15); = new JTextArea(5, 15); textArea.setLineWrap(truetextArea.setLineWrap(true); ); JScro

131、llPaneJScrollPane jspjsp = new = new JScrollPane(textAreaJScrollPane(textArea); ); getContentPane().add(jspgetContentPane().add(jsp, , BorderLayout.CENTERBorderLayout.CENTER);); pack(); pack();setDefaultCloseOperation(EXIT_ON_CLOSEsetDefaultCloseOperation(EXIT_ON_CLOSE); ); public static void main(S

132、tring public static void main(String argsargs) ) JTAreaAndJSPaneDemoJTAreaAndJSPaneDemo tptp = new = new JTAreaAndJSPaneDemoJTAreaAndJSPaneDemo(); (); tp.setVisible(truetp.setVisible(true);); v程序运行显示如下图所示。v9.3.7 列表框(JList)vJList类支持的列表框是允许用户从一个列表中选择一项或多项的组件。显示一个数组和向量的表是很容易的。列表框使用户易于操作大量的选项。列表框的所有项目都是

133、可见的,如果选项很多,超出了列表框可见区的范围,则列表框的旁边会有一个滚动条。vJList类的构造方法如下:JListJList() () 创建空模式的对象。JList(ObjectJList(Object listDatalistData) ) 构造显示指定数组listDatalistData中元素的JListJList对象。v例如,创建一个显示数组data中字符串的JList: String String data data = = one, one, two, two, three, three, four;four; JListJList dataListdataList = new

134、= new JList(dataJList(data););v【例9.18】使用JList。import import java.awtjava.awt.*;.*;import import javax.swingjavax.swing.*;.*;import import javax.swing.eventjavax.swing.event.*;.*;import import javax.swing.borderjavax.swing.border.*;.*;public class public class JListDemoJListDemo extends extends JFram

135、eJFrame public static void main(String public static void main(String argsargs) ) new new JListDemoJListDemo();(); private private JListJList jljl; ; private private JTextFieldJTextField valueFieldvalueField; ; public public JListDemoJListDemo() () super( super(一个简单的JListJList);); WindowUtilities.se

136、tNativeLookAndFeelWindowUtilities.setNativeLookAndFeel();(); addWindowListener(newaddWindowListener(new ExitListenerExitListener();(); Container content = Container content = getContentPanegetContentPane();(); String entries = String entries = “北京”, ,“上海”, , 天津,重庆,武汉;jljl = new = new JList(entriesJL

137、ist(entries); / ); / 创建JListJList对象jl.setVisibleRowCount(4); / jl.setVisibleRowCount(4); / 设置JListJList显示行数Font Font displayFontdisplayFont = new Font(Serif, Font.BOLD, 18); = new Font(Serif, Font.BOLD, 18);jl.setFont(displayFontjl.setFont(displayFont););jl.addListSelectionListener(newjl.addListSele

138、ctionListener(new ValueReporterValueReporter(); (); JScrollPaneJScrollPane listPanelistPane = new = new JScrollPane(jlJScrollPane(jl); ); JPanelJPanel listPanellistPanel = new = new JPanelJPanel();();listPanel.setBackground(Color.whitelistPanel.setBackground(Color.white););Border Border listPanelBor

139、derlistPanelBorder = = BorderFactoryBorderFactory. .createTitledBorder(JListcreateTitledBorder(JList数据););listPanel.setBorder(listPanelBorderlistPanel.setBorder(listPanelBorder);/);/设置面板边界listPanel.add(listPanelistPanel.add(listPane););content.add(listPanelcontent.add(listPanel, , BorderLayout.CENTE

140、RBorderLayout.CENTER););JLabelJLabel valueLabelvalueLabel = new = new JLabelJLabel(选择为:);:); valueLabel.setFont(displayFontvalueLabel.setFont(displayFont);); valueFieldvalueField = new = new JTextFieldJTextField(, 6);(, 6); valueField.setFont(displayFontvalueField.setFont(displayFont);); JPanelJPane

141、l valuePanelvaluePanel = new = new JPanelJPanel();(); valuePanel.setBackground(Color.whitevaluePanel.setBackground(Color.white);); Border Border valuePanelBordervaluePanelBorder = = BorderFactoryBorderFactory. . createTitledBorder(JListcreateTitledBorder(JList选择);); valuePanel.setBorder(valuePanelBo

142、rdervaluePanel.setBorder(valuePanelBorder);); valuePanel.add(valueLabelvaluePanel.add(valueLabel);); valuePanel.add(valueFieldvaluePanel.add(valueField);); content.add(valuePanelcontent.add(valuePanel, , BorderLayout.SOUTHBorderLayout.SOUTH);); pack(); pack(); setVisible(truesetVisible(true);); priv

143、ate class private class ValueReporterValueReporter implements implements ListSelectionListenerListSelectionListener public public void void valueChanged(ListSelectionEventvalueChanged(ListSelectionEvent event)event) if (! if (!event.getValueIsAdjustingevent.getValueIsAdjusting()() valueField.setText

144、valueField.setText( ( jl.getSelectedValue().toStringjl.getSelectedValue().toString();(); 程序的运行结果如图所示。v9.3.8 组合框(JComboBox)v在Java语言中,组合框有可编辑的和不可编辑的两种不同的形式。缺省是不可编辑的组合框。这里对不可编辑的组合框进行介绍。组合框用于在多项选择中选择一项的操作。在未选择组合框时,组合框显示为带按钮的一个选项的形式,当对组合框按键或单击时,组合框会打开可列出多项的一个列表,提供给用户选择。v类JComboBox提供组合框的支持,其相关类的层次如下: java

145、x.swing.Jcomponentjavax.swing.Jcomponent javax.swing.JComboBoxjavax.swing.JComboBoxv类JComboBox()的构造方法有四种,常用的有两种:JComboBox()用缺省的数据模式创建组合框。JComboBox(Object items)用指定数组创建组合框。v创 建 组 合 框 后 , 可 用 方 法 setSelectedIndex(int anIndex)选 定 指 定 下 标 anIndex处 的 项 目 ; 可 用 方 法 getSelectedIndex()获得选定项目的数组下标;可用方法getSel

146、ectedItem()获取选定的项目。v组合框事件是ActionEvent事件。事件处理方法与其他处理同类事件的方法类似。v【例9.19】使用JComboBox。import import java.awtjava.awt.*;.*;import import java.awt.eventjava.awt.event.*;.*;import import javax.swingjavax.swing.*;.*;public class public class JComboBoxDemoJComboBoxDemo extends extends JPanelJPanel JLabelJLabe

147、l picture,textpicture,text; ; public public JComboBoxDemoJComboBoxDemo() () String String pStringspStrings = = cup,cat,boy,girlcup,cat,boy,girl;JComboBoxJComboBox pListpList = new = new JComboBox(pStringsJComboBox(pStrings);); pList.setSelectedIndex(0); pList.setSelectedIndex(0); pList.addActionList

148、ener(newpList.addActionListener(new ActionListenerActionListener() () public void public void actionPerformed(ActionEventactionPerformed(ActionEvent e) e) JComboBoxJComboBox cbcb = ( = (JComboBox)e.getSourceJComboBox)e.getSource();(); String String pNamepName = ( = (String)cb.getSelectedItemString)c

149、b.getSelectedItem();(); picture.setIcon(newpicture.setIcon(new ImageIcon(imagesImageIcon(images/ /“ + + pNamepName + .gif); + .gif); text.setText(pNametext.setText(pName);); text.setHorizontalAlignment(JLabel.CENTERtext.setHorizontalAlignment(JLabel.CENTER);); ); ); picture = new picture = new JLabe

150、l(newJLabel(new ImageIcon(imagesImageIcon(images/ +/ + pStringspList.getSelectedIndexpStringspList.getSelectedIndex() +.gif);() +.gif);picture.setBorder(BorderFactorypicture.setBorder(BorderFactory. . createEmptyBorder(10,0,0,0); createEmptyBorder(10,0,0,0);picture.setPreferredSize(newpicture.setPre

151、ferredSize(new Dimension(180, 140); Dimension(180, 140);text text = = new new JLabel(pStringspList.getSelectedIndexJLabel(pStringspList.getSelectedIndex(),(), JLabel.CENTERJLabel.CENTER););setLayout(newsetLayout(new BorderLayoutBorderLayout();();add(pList,BorderLayout.NORTHadd(pList,BorderLayout.NOR

152、TH););add(picture,BorderLayout.CENTERadd(picture,BorderLayout.CENTER););add(text,BorderLayout.SOUTHadd(text,BorderLayout.SOUTH););setBordersetBorder( ( BorderFactory.createEmptyBorder(20,20,20,20); BorderFactory.createEmptyBorder(20,20,20,20); public static void main(String public static void main(S

153、tring argsargs) ) JFrameJFrame frame = new frame = new JFrameJFrame(使用JComboBoxJComboBox);); frame.setDefaultCloseOperationframe.setDefaultCloseOperation( ( JFrame.EXIT_ON_CLOSEJFrame.EXIT_ON_CLOSE); ); frame.setContentPane(newframe.setContentPane(new JComboBoxDemoJComboBoxDemo();();frame.packframe.

154、pack();(); frame.setVisible(trueframe.setVisible(true);); v程序的运行结果如下图所示。v9.3.9 滚动条(JSlider)v在某些程序中,需要调整线性的值,这时就需要滚动条。滚动条提供了易于操作的值的范围或区的范围。javax.swing.JSlider类提供了对滚动条的支持,它的父类是javax.swing.JComponent类。v可用下列JSlider类的构造方法生成JSlider对象。JSliderJSlider() () 创建范围为0 0至100100,初值为5050的水平滚动条。JSlider(intJSlider(int

155、 orientation) orientation) 创建范围为0 0至100100,初值为5050的 水 平 或 垂 直 滚 动 条 。 表 示 方 向 的 值 可 为 常 量JSlider.HORIZONTALJSlider.HORIZONTAL和JSlider.VERTICALJSlider.VERTICAL,分别表示水平和垂直方向。JSlider(intJSlider(int min, min, intint max) max) 创建范围为minmin至maxmax,初值为minmin和maxmax平均值的水平滚动条。 JSlider(intJSlider(int min, min,

156、intint max, max, intint value) value) 创建范围为minmin至maxmax,初值为valuevalue的水平滚动条。JSlider(intJSlider(int orientation, orientation, intint min, min, intint max, max, intint value) value) 创建范围为minmin至maxmax,初值为valuevalue的水平或垂直滚动条。v对创建的JSlider对象可显示数据刻度和数据值,也可设置边界等。与其他接口组件一样,滚动条产生一个可以控制的事件ChangeEvent。v【例9.20

157、】使用JSlider。import import java.awtjava.awt.*;.*;import import javax.swingjavax.swing.*;.*;import import javax.swing.eventjavax.swing.event.*;.*;public class public class JSliderDemoJSliderDemo extends extends JframeJframe implements implements ChangeListenerChangeListener JLabelJLabel l1; l1;intint v

158、1,v2; v1,v2;JSliderJSlider sl1,sl2; sl1,sl2;public static void main(String public static void main(String argsargs) ) new new JSliderDemoJSliderDemo();(); public public JSliderDemoJSliderDemo() () super( super(使用JSliderJSlider);); Container c = Container c = getContentPanegetContentPane();(); c.setB

159、ackground(Color.whitec.setBackground(Color.white);); sl1 = new JSlider(JSlider.VERTICAL,100,200,100); sl1 = new JSlider(JSlider.VERTICAL,100,200,100); / / 创建垂直滚动条 sl1.setMajorTickSpacing(50); / sl1.setMajorTickSpacing(50); / 设置大刻度间隔 sl1.setMinorTickSpacing(10); / sl1.setMinorTickSpacing(10); / 设置小刻度

160、间隔 sl1.setPaintTicks(true); / sl1.setPaintTicks(true); / 显示刻度 sl1.setPaintLabels(true); / sl1.setPaintLabels(true); / 显示标注sl1.addChangeListener(this); / sl1.addChangeListener(this); / 注册监听器c.add(sl1, c.add(sl1, BorderLayout.WESTBorderLayout.WEST););sl2 = new sl2 = new JSliderJSlider(); / (); / 创建水平滚

161、动条sl2.setBorder(sl2.setBorder( BorderFactory.createTitledBorderBorderFactory.createTitledBorder( ( JSliderJSlider( (具有带标题的边框、刻度和标注);); / / 设置组件带标题的边界sl2.setMajorTickSpacing(20);sl2.setMajorTickSpacing(20);sl2.setMinorTickSpacing(5);sl2.setMinorTickSpacing(5);sl2.setPaintTicks(true); /true:sl2.setPai

162、ntTicks(true); /true:产生滚动条上的刻度sl2.setPaintLabels(true); /true:sl2.setPaintLabels(true); /true:显示刻度上的数据sl2.addChangeListener(this);sl2.addChangeListener(this);c.add(sl2,BorderLayout.SOUTH);c.add(sl2,BorderLayout.SOUTH); l1=new l1=new JLabelJLabel( ( 垂直滚动条的值为:+ 100+ 100+水平滚动条的值为:+50);+50); c.add(l1,Bo

163、rderLayout.CENTER); c.add(l1,BorderLayout.CENTER); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSEsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);); / / 设置框架关闭按钮事件 pack(); pack(); setVisible(truesetVisible(true);); public void public void stateChanged(ChangeEventstateChanged(ChangeEvent e) e) if(e.getS

164、ourceif(e.getSource()=sl1)()=sl1) v1=( v1=(JSlider)e.getSource().getValueJSlider)e.getSource().getValue();(); else else if(e.getSourceif(e.getSource()=sl2) ()=sl2) v2=( v2=(JSlider)e.getSource().getValueJSlider)e.getSource().getValue();(); l1.setText( l1.setText(垂直滚动条的值为:+v1+v1+ , ,水平滚动条的值为:+v2);v2)

165、; v程序运行结果如下图所示。v9.3.10 菜单(JMenu)v菜单将一个应用程序的命令按层次化管理并组织在一起,是一种常用的GUI组件。常见的菜单为下拉式菜单和弹出式菜单(快捷菜单)等。v下拉式菜单包含有一个菜单条(也称为菜单栏,MenuBar),在菜单条上安排有若干个菜单(Menu),每个菜单又包含若干菜单项(MenuItem),每个菜单项对应了一个命令或子菜单项。它们构成一个应用程序的菜单系统。用鼠标或键盘选择对应一个命令的菜单项与选择一个按钮类似。使用菜单系统可方便地向程序分布命令。v在构建一个自己的菜单系统时,可按照菜单系统的层次,一步一步地进行。v(1)用类JMenuBar创建菜

166、单条v可简单地用JMenuBar()构造方法类创建一个新菜单条。例如,JMenuBarJMenuBar aMenuBaraMenuBar = new = new JMenuBarJMenuBar();();v(2)用类JMenu创建菜单v用类JMenu的构造方法来创建菜单,其构造方法有:public public JMenuJMenu()()构造一个无文本的菜单。public public JMenu(StringJMenu(String s)s)用字符串s s作为文本来构造一个菜单。v例如: JMenu aMenu = new JMenu(文件); / 创建“文件”菜单v(3)用类JMenu

167、Item创建菜单项v类JMenuItem的构造方法有:public public JMenuItemJMenuItem()()创建一个菜单项,但不设置文本和图标。public public JMenuItem(IconJMenuItem(Icon icon) icon)创建一个带图标的菜单项。public public JMenuItem(StringJMenuItem(String text)text)创建一个具有指定文本的菜单项。public public JMenuItem(StringJMenuItem(String text, text, Icon Icon icon)icon)创建

168、具有文本和图标的菜单项。public public JMenuItem(StringJMenuItem(String text,inttext,int mnemonic)mnemonic)创建具有文本和快捷字母的菜单项。v例如:JMenuItem aMenuItem = new JMenuItem(新建);/ 创建“新建”菜单项v(4)将菜单项加入到菜单中,将菜单加入到菜单条中 v可用JMenuBar类和JMenu类的add()方法完成添加工作。例如: aMenuBar.add(aMenu ); aMenu.add(aMenuItem);v另外,可用addSeparator()方法向菜单添加分

169、隔线。v(5)将菜单条加入容器中v可向实现了MenuContainer接口的容器(如框架)加入菜单系统。在框架JFrame类中有方法: public void setJMenuBar(JMenuBar menubar)v可为框架设置菜单条。例如: JFrame aFrame = new JFrame(); aFrame.setJMenuBar(aMenuBar);v(6)处理菜单项选择事件v为了检测对菜单项作出的选择,要监听菜单项ActionEvent事件,选择一个菜单项正如选择了一个JButton按钮一样。事件处理的相关代码可见下例。v【例9.21】使用下拉菜单系统。 import impo

170、rt javax.swingjavax.swing.*;.*;import import java.awtjava.awt.*;.*;import import java.awt.eventjava.awt.event.*;.*;public class public class JMenuDemoJMenuDemo extends extends JFrameJFrame implements implements ActionListenerActionListener JLabelJLabel j1 = new j1 = new JLabelJLabel( ( 请选择菜单:,JLabel

171、.CENTERJLabel.CENTER);); JMenuItemJMenuItem aaMenuItem,baMenuItemaaMenuItem,baMenuItem; ; JMenuDemoJMenuDemo()() super( super(使用JMenuJMenu);); JMenuBarJMenuBar aMenuBaraMenuBar = new = new JMenuBarJMenuBar();(); Icon i1 = new Icon i1 = new ImageIcon(images/girl.gifImageIcon(images/girl.gif););Icon i

172、2 = new Icon i2 = new ImageIcon(images/boy.gifImageIcon(images/boy.gif););JMenuJMenu aMenuaMenu = new = new JMenuJMenu(菜单A);A);JMenuJMenu bMenubMenu = new = new JMenuJMenu(菜单B);B);JMenuItemJMenuItem aaMenuItemaaMenuItem = new = new JMenuItemJMenuItem(菜单项AA,i1);AA,i1);JMenuItemJMenuItem abMenuItemabM

173、enuItem = new = new JMenuItemJMenuItem(菜单项AB,i2);AB,i2);JMenuItemJMenuItem baMenuItembaMenuItem = new = new JMenuItemJMenuItem(菜单项BA);BA);aMenuBar.add(aMenuaMenuBar.add(aMenu););aMenuBar.add(bMenuaMenuBar.add(bMenu););aMenu.add(aaMenuItemaMenu.add(aaMenuItem););aMenu.addSeparatoraMenu.addSeparator()

174、;();aMenu.add(abMenuItemaMenu.add(abMenuItem););bMenu.add(baMenuItembMenu.add(baMenuItem););aaMenuItem.addActionListener(thisaaMenuItem.addActionListener(this););abMenuItem.addActionListener(thisabMenuItem.addActionListener(this););baMenuItem.addActionListener(thisbaMenuItem.addActionListener(this);

175、);setJMenuBar(aMenuBarsetJMenuBar(aMenuBar);); getContentPane().add(j1,BorderLayout.CENTER); getContentPane().add(j1,BorderLayout.CENTER); public void public void actionPerformed(ActionEventactionPerformed(ActionEvent e) e) JMenuItemJMenuItem source = ( source = (JMenuItem)(e.getSourceJMenuItem)(e.g

176、etSource();(); j1.setText( j1.setText(选择了菜单:+:+source.getTextsource.getText();(); j1.setHorizontalAlignment(JLabel.CENTER); j1.setHorizontalAlignment(JLabel.CENTER); public static void main(String public static void main(String argsargs) JFrameJFrame frame = new frame = new JMenuDemoJMenuDemo();();

177、frame.setDefaultCloseOperationframe.setDefaultCloseOperation( ( JFrame.EXIT_ON_CLOSEJFrame.EXIT_ON_CLOSE);); frame.setVisible(trueframe.setVisible(true);); frame.pack(); frame.pack(); v程序运行时选择了菜单A后的情况如下图所示。v9.3.11对话框v对话框是一种大小不能变化、不能有菜单的容器窗口,对话框不能作为一个应用程序的主框架,而必须包含在其他的容器中。Java语言提供多种对话框类来支持多种形式的对话框。 J

178、OptionPane类支持简单、标准的对话框;JDialog类支持定制用户自己的对话框;JFileChooser类 支 持 文 件 打 开 、 保 存 对 话 框 ;ProgressMonitor类支持操作进度条控制对话框等。v对话框依赖于框架。当框架撤销时,依赖该框架的对话框也撤销。当框架图标化时,依赖它的对话框也从屏幕上消失。当框架窗口恢复时,依赖框架的对话框又返回屏幕。v下面介绍较简单的JOptionPane和JFileChooser类支持的对话框。 v1. JOptionPane对话框vJOptionPane提供的对话框是模式对话框。当模式对话框显示时,它不允许用户输入到程序的其他的窗

179、口。使用JOptionPane,可以创建和自定义问题、信息、警告和错误等几种类型的对话框。JOptionPane提供标准对话框的布局支持、图标、指定对话框的标题和文本、自定义按钮文本、允许自定义组件的对话框显示、指定对话框在屏幕上的显示位置等特性。vjavax.swing.JOptionPane类继承于javax.swing.JComponent类,有七种构造方法,常用的有五种:JOptionPaneJOptionPane()()创建具有测试信息的JOptionPaneJOptionPane对象。JOptionPane(ObjectJOptionPane(Object message) mes

180、sage) 创建显示messagemessage和缺省选项的JOptionPaneJOptionPane对象。JOptionPane(ObjectJOptionPane(Object message, message, intint messageTypemessageType) ) 创建以messageTypemessageType类 型 显 示 messagemessage和 使 用 缺 省 选 项 的JOptionPaneJOptionPane对象。JOptionPane(ObjectJOptionPane(Object message, message, intint messageT

181、ypemessageType, , intint optionTypeoptionType) )创建显示指定类型信息和指定选项类型的JOptionPaneJOptionPane对象。JOptionPane(ObjectJOptionPane(Object message, message, intint messageTypemessageType, , intint optionTypeoptionType, , Icon Icon icon) icon) 创建显示指定类型信息和指定选项类型、图标的JOptionPaneJOptionPane对象。v要显示简单的模式对话框,可以使用showM

182、essageDialog()或 showOptionDialog()方 法 。 它 们 的 格 式 为 ( showMessageDialog()方法有重载):public public static static void void showMessageDialog(ComponentshowMessageDialog(Component parentComponent,ObjectparentComponent,Object message,String message,String title,inttitle,int messageType,IconmessageType,Icon

183、icon)throws icon)throws HeadlessExceptionHeadlessExceptionpublic public static static intint showOptionDialog(ComponentshowOptionDialog(Component parentComponent,ObjectparentComponent,Object message,String message,String title,inttitle,int optionType,intoptionType,int messageType,IconmessageType,Ico

184、n icon,Object icon,Object options,Object options,Object initialValueinitialValue) ) throws throws HeadlessExceptionHeadlessExceptionv前者显示一个带一个“Ok”或“确定”按钮的对话框。后者显示自定义的对话框可以显示具有定制文本的各种按钮,并可包含一个标准的文本信息或组件集合。 例如:JOptionPane.showMessageDialogJOptionPane.showMessageDialog( ( frame, frame,请输入一个整数。 n + n +

185、无效输入。););vshowXxxDialog方法的所有参数和JOptionPane构造方法都是标准化的, 下面对这些参数进行说明。parentComponentparentComponent 对每个showXxxDialogshowXxxDialog方法的第一个参数总是父组件,必须是一个框架、一个框架中的组件、或nullnull值。JOptionPaneJOptionPane构造方法不包含这个参数。message message 这个必须的参数指明要显示的对话框。一般是一个字符串,显示在对话框的一个标签中。title title 标题。optionTypeoptionType 指定出现在对话

186、框底部的按钮集合,可以选择下面4 4个标准集合之一: : DEFAULT_OPTIONDEFAULT_OPTION,YES_NO_OPTIONYES_NO_OPTION,YES_NO_CANCEL_OPTIONYES_NO_CANCEL_OPTION,OK_CANCEL_OPTIONOK_CANCEL_OPTION。messageTypemessageType 确定显示在对话框中的图标。从下列值中选择一 个 : PLAIN_MESSAGE PLAIN_MESSAGE ( (无 icon), icon), ERROR_MESSAGE, ERROR_MESSAGE, INFORMATION_MES

187、SAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE. QUESTION_MESSAGE. icon icon 指明了在对话框中显示用户定义图标。optionsoptions进一步指明任选对话框底部的按钮。一般地,对按钮指定一个字符串数组。initialValueinitialValue 指明选择的初始值。vshowMessageDialog()和showOptionDialog()方法返回用 户 选 择 的 一 个 整 数 , 整 数 值 为 YES_OPTION, NO_OPTION, C

188、ANCEL_OPTION, OK_OPTION和CLOSED_OPTION之一。除了CLOSED_OPTION的每一个选项都对应用户单击的按钮。当CLOSED_OPTION返回时,说明用户关闭了对话框窗口。v即使用户改变了标准对话框上按钮显示的字符串,返回值仍然为预定义的整数值之一。例如,一个YES_NO_OPTION对 话 框 总 是 返 回 下 列 值 之 一 :YES_OPTION、NO_OPTION或CLOSED_OPTION。v【例9.22】使用对话框。 import import javax.swingjavax.swing.*;.*;import import java.awtj

189、ava.awt.*;.*;import import java.awt.eventjava.awt.event.*;.*;public class public class JOptionPaneDemoJOptionPaneDemo public public JFrameJFrame aFrameaFrame; ; public public JButtonJButton aButtonaButton; ; public JOptionPane public JOptionPane anOptionPaneanOptionPane; ; static static JLabelJLabel

190、 aLabelaLabel; ; public public JOptionPaneDemoJOptionPaneDemo()() aFrameaFrame = new = new JFrameJFrame(使用JOptionPane);JOptionPane); aButtonaButton = new = new JButtonJButton(显示对话框);); aLabelaLabel = new = new JLabelJLabel( (“您作出的选择是:”, , JLabel.CENTERJLabel.CENTER);); aButton.addActionListener(newa

191、Button.addActionListener(new OptionListenerOptionListener();(); anOptionPaneanOptionPane = new JOptionPane(); = new JOptionPane();aFrame.setSize(300,200);aFrame.setSize(300,200);aFrame.getContentPane().add(aButtonaFrame.getContentPane().add(aButton, , BorderLayout.NORTHBorderLayout.NORTH););aFrame.g

192、etContentPane().add(aLabelaFrame.getContentPane().add(aLabel, , BorderLayout.SOUTHBorderLayout.SOUTH););aFrame.setVisible(trueaFrame.setVisible(true););aFrame.setDefaultCloseOperationaFrame.setDefaultCloseOperation( ( JFrame.EXIT_ON_CLOSEJFrame.EXIT_ON_CLOSE);); public public class class OptionListe

193、nerOptionListener implements implements ActionListenerActionListener public void public void actionPerformed(ActionEventactionPerformed(ActionEvent e) e) String choices = String choices = 喜欢, , 不喜欢; ; intint n = n = anOptionPane.showOptionDialog(aFrameanOptionPane.showOptionDialog(aFrame, , 您喜欢音乐吗?

194、, , 请选择 , , JOptionPane.YES_NO_OPTIONJOptionPane.YES_NO_OPTION, , JOptionPane.QUESTION_MESSAGEJOptionPane.QUESTION_MESSAGE, null, null, choices,choices0); choices,choices0);if(n = 0)if(n = 0) JOptionPaneDemo.aLabel.setTextJOptionPaneDemo.aLabel.setText(喜欢音乐);); else else JOptionPaneDemo.aLabel.setTe

195、xtJOptionPaneDemo.aLabel.setText(不喜欢音乐);); public static void main( String public static void main( String argsargs) ) new new JOptionPaneDemoJOptionPaneDemo();(); v程序运行时显示的 对话框如下图所示。v2.JFileChooser对话框vJFileChooser类提供对文件的打开、关闭等文件操作的标准对话框。vJFileChooser类继承于JComponent类,其构造方法有:JFileChooserJFileChooser()

196、()构造一个指向用户缺省目录的JFileChooserJFileChooser对象 。JFileChooser(FileJFileChooser(File currentDirectorycurrentDirectory) )构造一个以给定FileFile为路径的JFileChooserJFileChooser对象。v构 造 JFileChooser对 象 后 , 要 利 用 该 类 的 方 法 showOpenDialog()或showSaveDialog()来显示文件打开或文件关闭对话框。它们的格式为:public public intint showOpenDialog(Componen

197、tshowOpenDialog(Component parent)throws parent)throws HeadlessExceptionHeadlessExceptionpublic public intint showSaveDialog(ComponentshowSaveDialog(Component parent)throws parent)throws HeadlessExceptionHeadlessExceptionv它们的参数都是包含对话框容器的对象。返回值为下面几种情况:JFileChooser.CANCEL_OPTIONJFileChooser.CANCEL_OPTI

198、ON 表示选择了“撤消”按钮。JFileChooser.APPROVE_OPTIONJFileChooser.APPROVE_OPTION 表示选择了“打开”或“保存”按钮。JFileChooser.ERROR_OPTIONJFileChooser.ERROR_OPTION 表示出现错误。v在打开或关闭文件对话框中作出选择后,可用JFileChooser类的方法getSelectedFile()返回选取的文件名(File类的对象)。v【 例 9.23】 使 用 文 件 打 开 、 关 闭 对 话 框(JFileChooser)。将选择的文件名显示到文本区域中。import import jav

199、a.iojava.io.*;.*;import import java.awtjava.awt.*;.*;import import java.awt.eventjava.awt.event.*;.*;import import javax.swingjavax.swing.*;.*;import import javax.swing.filechooserjavax.swing.filechooser.*;.*;public class public class JFileChooserDemoJFileChooserDemo extends extends JFrameJFrame pub

200、lic public JFileChooserDemoJFileChooserDemo() () super( super(使用JFileChooser);JFileChooser); final final JTextAreaJTextArea tata = new JTextArea(5,20); = new JTextArea(5,20); ta.setMargin(newta.setMargin(new Insets(5,5,5,5); Insets(5,5,5,5); ta.setEditable(falseta.setEditable(false);); JScrollPaneJS

201、crollPane sp = new sp = new JScrollPane(taJScrollPane(ta);); final JFileChooser final JFileChooser fcfc = new JFileChooser(); = new JFileChooser(); JButtonJButton openBtnopenBtn = new = new JButtonJButton(打开文件.);.);openBtn.addActionListener(newopenBtn.addActionListener(new ActionListenerActionListen

202、er()() public void public void actionPerformed(ActionEventactionPerformed(ActionEvent e) e) intint returnValreturnVal = = fc.showOpenDialogfc.showOpenDialog( ( JFileChooserDemo.thisJFileChooserDemo.this);); if if ( (returnValreturnVal = = JFileChooser.APPROVE_OPTION) JFileChooser.APPROVE_OPTION) Fil

203、e file = File file = fc.getSelectedFilefc.getSelectedFile();(); ta.appendta.append(打开: + : + file.getNamefile.getName() + .n);() + .n); else else ta.appendta.append(取消打开命令.n);n); ); );JButtonJButton saveBtnsaveBtn = new = new JButtonJButton(保存文件.);.);saveBtn.addActionListener(newsaveBtn.addActionLis

204、tener(new ActionListenerActionListener()() public void public void actionPerformed(ActionEventactionPerformed(ActionEvent e) e) intint returnValreturnVal = = fc.showSaveDialogfc.showSaveDialog( ( JFileChooserDemo.thisJFileChooserDemo.this););if (if (returnValreturnVal = JFileChooser.APPROVE_OPTION)

205、= JFileChooser.APPROVE_OPTION)File file = File file = fc.getSelectedFilefc.getSelectedFile();();ta.append(Savingta.append(Saving: + : + file.getNamefile.getName() + .n);() + .n); else else ta.appendta.append(取消保存命令。 n);n); ););JPanelJPanel buttonPanelbuttonPanel = new = new JPanelJPanel();();buttonP

206、anel.add(openBtnbuttonPanel.add(openBtn););buttonPanel.add(saveBtnbuttonPanel.add(saveBtn););openBtn.setNextFocusableComponent(saveBtnopenBtn.setNextFocusableComponent(saveBtn););saveBtn.setNextFocusableComponent(openBtnsaveBtn.setNextFocusableComponent(openBtn););Container c = Container c = getCont

207、entPanegetContentPane();();c.add(buttonPanelc.add(buttonPanel, , BorderLayout.NORTHBorderLayout.NORTH););c.add(sp, c.add(sp, BorderLayout.CENTERBorderLayout.CENTER);); public static void main(String public static void main(String argsargs) ) JFrameJFrame frame = new frame = new JFileChooserDemoJFile

208、ChooserDemo();(); frame.setDefaultCloseOperation(EXIT_ON_CLOSEframe.setDefaultCloseOperation(EXIT_ON_CLOSE);); frame.pack(); frame.pack(); frame.setVisible(trueframe.setVisible(true);); v程序运行的开始界面如下图左,选择“打开文件”按钮后,即出现下图右的打开文件对话框,选择文件后将选择文件名显示到文本区域中。选择“保存文件”按钮,将出现文件保存对话框。例9.23的运行界面。9.4 鼠标和键盘事件v在GUI程序中

209、,通常使用鼠标来进行人机交互操作。鼠标的移动、单击、双击等都会引发鼠标事件。为输入数据、操作命令等,也使用键盘。键盘的按下,释放也会引发键盘事件。下面简单介绍AWT的鼠标和键盘事件的处理。v9.4.1 鼠标事件v处理鼠标事件的程序要实现在java.awt.event包中定义的两个接口MouseListener和MouseMotionListener,在这两个接口中定义了未实现的鼠标事件处理方法。v接口MouseListener中的方法为:public public void void mousePressed(MouseEventmousePressed(MouseEvent e)e)处理按下

210、鼠标左键public void public void mouseClicked(MouseEventmouseClicked(MouseEvent e) e)处理鼠标单击public public void void mouseReleased(MouseEventmouseReleased(MouseEvent e)e)处理鼠标按键释放public public void void mouseEntered(MouseEventmouseEntered(MouseEvent e)e)处理鼠标进入当前窗口public public void void mouseExited(MouseEve

211、ntmouseExited(MouseEvent e)e)处理鼠标离开当前窗口v接口MouseMotionListener中的方法为:public void public void mouseDragged(MouseEventmouseDragged(MouseEvent e) e)处理鼠标拖动public void public void mouseMoved(MouseEventmouseMoved(MouseEvent e) e)处理鼠标移动v对应上述接口,对应的注册监听器的方法是addMouseListener()和addMouseMotionListener()。v另外,类Mous

212、eEvent的方法getX()、getY()常用来获取鼠标当前所在位置的坐标,它们的格式如下:public public intint getXgetX()()public public intint getYgetY()()v【例9.24】通过单击鼠标来画蓝色的圆点。import import javax.swingjavax.swing.*;.*;import import java.awt.eventjava.awt.event.*;.*;import import java.awtjava.awt.*;.*;public class public class MouseEventDem

213、oMouseEventDemo extends extends JAppletJApplet public void init() public void init() addMouseListener(newaddMouseListener(new CircleListenerCircleListener();(); setForeground(Color.bluesetForeground(Color.blue);); setBackground(Color.whitesetBackground(Color.white);); class class CircleListenerCircl

214、eListener extends extends MouseAdapterMouseAdapter private private intint radius = 10; radius = 10; public void public void mousePressed(MouseEventmousePressed(MouseEvent e) e) JAppletJApplet app = ( app = (JApplet)e.getSourceJApplet)e.getSource();();Graphics g = Graphics g = app.getGraphicsapp.getG

215、raphics();(); g.fillOval(e.getX()-radius,e.getY()-radiusg.fillOval(e.getX()-radius,e.getY()-radius, , 2*radius,2*radius); 2*radius,2*radius); v程序运行结果如下图所示。v9.4.2 键盘事件v处理键盘事件的程序要实现在java.awt.event包中定义的接口KeyListener,在这个接口中定义了未实现的键盘事件处理方法。键盘事件处理方法为:public void public void KeyPressed(KeyEventKeyPressed(K

216、eyEvent e) e)处理按下键。public void public void KeyReleased(KeyEventKeyReleased(KeyEvent e) e)处理松开键。public void public void KeyTyped(KeyEventKeyTyped(KeyEvent e) e)处理敲击键盘。v为识别引发键盘事件的按键,常用到KeyEvent类的如下方法:public public char char getKeyChargetKeyChar()()返回该事件中键的字符。例如,shift + ashift + a按键事件返回值为 AA。public pub

217、lic static static String String getKeyText(intgetKeyText(int keyCodekeyCode) )返回描述键代码的字符串,例如 HOMEHOME、F1 F1 或 AA等。 v【例9.24】综合鼠标事件和键盘事件处理的程序,模拟一个电子白板,可以用鼠标在上面绘画,可用键盘在上面写字。import import javax.swingjavax.swing.*;.*;import import java.awtjava.awt.*;.*;import import java.awt.eventjava.awt.event.*;.*;publ

218、ic class public class MouseAndKeyDemoMouseAndKeyDemo extends extends JAppletJApplet protected protected intint lastXlastX = 0, = 0, lastYlastY = 0; = 0; public void init() public void init() setBackground(Color.whitesetBackground(Color.white);); setForeground(Color.bluesetForeground(Color.blue);); a

219、ddMouseListener(newaddMouseListener(new PositionRecorderPositionRecorder();(); addMouseMotionListener(newaddMouseMotionListener(new LineDrawerLineDrawer();(); addKeyListener(newaddKeyListener(new CharDrawerCharDrawer();(); protected void protected void record(intrecord(int x, x, intint y) y) lastXla

220、stX = x; = x; lastYlastY = y; = y; private class private class PositionRecorderPositionRecorder extends extends MouseAdapterMouseAdapter public void public void mouseEntered(MouseEventmouseEntered(MouseEvent e) e) requestFocusrequestFocus();(); record(e.getXrecord(e.getX(), (), e.getYe.getY();(); pu

221、blic void public void mousePressed(MouseEventmousePressed(MouseEvent e) e) record(e.getXrecord(e.getX(), (), e.getYe.getY();(); private class private class LineDrawerLineDrawer extends extends MouseMotionAdapterMouseMotionAdapter public void public void mouseDragged(MouseEventmouseDragged(MouseEvent

222、 e) e) intint x = x = e.getXe.getX()(),y = y = e.getYe.getY(); (); Graphics g = Graphics g = getGraphicsgetGraphics();(); g.drawLine(lastXg.drawLine(lastX, , lastYlastY, x, y);, x, y); record(x, y); record(x, y); private class private class CharDrawerCharDrawer extends extends KeyAdapterKeyAdapter p

223、ublic void public void keyTyped(KeyEventkeyTyped(KeyEvent event) event) String s = String s = String.valueOf(event.getKeyCharString.valueOf(event.getKeyChar();(); getGraphics().drawString(sgetGraphics().drawString(s, , lastXlastX, , lastYlastY); ); record(lastXrecord(lastX + 11, + 11, lastYlastY);); v程序中,在类MouseAndKeyDemo中定义了三个私有嵌套类,两个类对鼠标事件进行处理,一个类对键盘事件进行处理。v程序的运行情况如下图所示。图中的线用鼠标随手画出,文字用键盘输入。

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 医学/心理学 > 基础医学

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号