Java图形用户界面设计AWT_第1页
Java图形用户界面设计AWT_第2页
Java图形用户界面设计AWT_第3页
Java图形用户界面设计AWT_第4页
Java图形用户界面设计AWT_第5页
已阅读5页,还剩107页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、目标重点难点n【课前思考】【课前思考】1 java语言是跨平台的编程语言,那么图形用户界面如何做到跨平台?2 AWT有哪些组件和容器?它们各自的使用方法是什么?3 AWT的事件处理模型是什么?原理又如何?n【学习目标】【学习目标】掌握用AWT来设计图形用户界面的方法,尤其是组件、容器、布局管理器等概念。学习AWT事件处理模型,掌握事件源、事件、事件处理者等概念,让程序能够响应用户的操作。最后了解AWT各个组件的用法及所采用的事件处理接口。n【学习指南】【学习指南】理解概念,多实践,勤思考,举一反三。n【难【难 重重 点】点】 重点:重点:事件处理模型。难点:难点:内部类匿名类在AWT中的应用。

2、图形用户界面设计n使用AWT构造GUIq组件q容器q布局管理nAWT 事件处理模型nAWT 组件使用AWT构造njava.awt包提供了基本的java程序的GUI设计工具。qComponentqContainerqLayoutManagerJava.lang.ObjectAWTEventFontComponetGraphicsMenuComponent各种布局管理器类ContainerPanelAppletWindowFrameComponent(组件)nJava的图形用户界面的最基本组成部分是组件,组件是一个可以以图形化的方式显示在屏幕上并能与用户进行交互的对象,例如一个按钮,一个标签等。n

3、组件不能独立地显示出来,必须将组件放在一定的容器中才可以显示出来。n组件的一般功能q基本的绘画支持 q外形控制 q大小和位置控制 q图像处理 q组件的状态控制 Container(容器)n容器(Container)实际上是Component的子类,因此容器本身也是一个组件,具有组件的所有性质,另外还具有容纳其它组件和容器的功能。n主要功能q组件的管理 q布局管理 Graphics类 nGraphics是所有用来在组件上进行图形绘制时所使用的图形环境上下文的父类.n它提供了对组件进行绘制的一般方法和接口n封装了用来进行图形绘制时必须的状态信息 q要绘制的组件对象q当前颜色q当前字体q当前逻辑点操

4、作的功能(Xor或者paint)q当前XOR方式的替代颜色。LayoutManager(布局管理器)n为了使我们生成的图形用户界面具有良好的平台无关性,Java语言中,提供了布局管理器这个工具来管理组件在容器中的布局,而不使用直接设置组件位置和大小的方式。n每个容器都有一个布局管理器,当容器需要对某个组件进行定位或判断其大小尺寸时,就会调用其对应的布局管理器。n在程序中安排组件的位置和大小时,应该注意:q容器中的布局管理器负责各个组件的大小和位置,因此用户无法在这种情况下设置组件的这些属性。如果试图使用Java语言提供的setLocation(),setSize(),setBounds()等方

5、法,则都会被布局管理器覆盖。q如果用户确实需要亲自设置组件大小或位置,则应取消该容器的布局管理器,方法为:setLayout(null);常用容器nFramenPanelnAppletFramejava.lang.Object | +-java.awt.Component | +-java.awt.Container | +-java.awt.Window | +-java.awt.Frameimport java.awt.*;public class MyFrame extends Framepublic static void main(String args )MyFrame fr =

6、new MyFrame(Hello Out There!);fr.setSize(200,200);fr.setBackground(Color.red);fr.setVisible(true);public MyFrame (String str)super(str);n运行结果Paneljava.lang.Object | +-java.awt.Component | +-java.awt.Container | +-java.awt.Panelimport java.awt.*;public class FrameWithPanel extends Framepublic FrameWi

7、thPanel(String str)super(str);public static void main(String args)FrameWithPanel fr = new FrameWithPanel(Frame with Panel);Panel pan=new Panel();fr.setSize(200,200);fr.setBackground(Color.red);fr.setLayout(null);pan.setSize(100,100);pan.setBackground(Color.yellow);fr.add(pan);fr.setVisible(true);n运行

8、结果:LayoutManagernFlowLayoutnBorderLayoutnGridLayoutnCardLayoutnGridBagLayoutimport java.awt.*;public class ExGuiprivate Frame f;private Button b1;private Button b2;public static void main(String args)ExGui that = new ExGui();that.go();public void go()f = new Frame(GUI example);f.setLayout(new FlowLa

9、yout();b1 = new Button(Press Me);b2 = new Button(Dont Press Me);f.add(b1);f.add(b2);f.pack();f.setVisible(true);n运行结果FlowLayoutnPanel,Applet的缺省布局管理器。setLayout(new FlowLayout(FlowLayout.RIGHT,20,40);setLayout( (new FlowLayout FlowLayout.LEFT); setLayout(new FlowLayout();第1个参数设置对齐方向(alignment ),缺省情况是居

10、中,第2,3个参数设置横向和纵向的间隔(gap),缺省值是5 import java.awt.*; public class myButtons public static void main(String args) Frame f = new Frame(); f.setLayout(new FlowLayout(); Button button1 = new Button(Ok); Button button2 = new Button(Open); Button button3 = new Button(Close); f.add(button1); f.add(button2); f

11、.add(button3); f.setSize(300,100); f.setVisible(true); 运行结果为:BorderLayoutnWindow,Frame和Dialog的缺省布局管理器。BorderLayout布局管理器包括5个区域:North,South,East,West和Center。添加组件时,必须指明添加位置.否则无法显示.import java.awt.*;public class buttonDir public static void main(String args) Frame f = new Frame(BorderLayout); f.setLayou

12、t(new BorderLayout(); f.add(North, new Button(North); f.add(South, new Button(South); f.add(East, new Button(East); f.add(West, new Button(West); f.add(Center, new Button(Center); f.setSize(200,200); f.setVisible(true); 运行结果GridLayoutn使容器中各个组件呈网格状布局。从上到下,从左到右一次排列.import java.awt.*;public class Butto

13、nGrid public static void main(String args)Frame f = new Frame(GridLayout);f.setLayout(new GridLayout(3,2);f.add(new Button(1); f.add(new Button(2); f.add(new Button(3); f.add(new Button(4); f.add(new Button(5); f.add(new Button(6); f.setSize(200,200); f.setVisible(true);运行结果CardLayoutnCardLayout布局管理

14、器能够帮助用户处理两个以至更多的成员共享同一显示空间。import java.awt.*;import java.awt.event.*;public class ThreePages implements MousListener CardLayout layout=new CardLayout();Frame f=new Frame(“CardLayout”);Button page1Button;Label page2Label;TextArea page3Text;Button page3Top;Button page3Bottom;public static void main(St

15、ring args) new ThreePages().go(); Public void go() f.setLayout(layout);f.add(page1Button=new Button(“Button page”) , “page1Button”);page1Button.addMouseListener(this);f.add(page2Label=new Label(“Label page”) ,“page2Label”);page2Label.addMouseLisener(this);/注册监听器Panel panel=new Panel();panel.setLayou

16、t(new BorderLayout();panel.add(page3Text=new TextArea(“Composite page”), “Center”);page3Text.addMouseListener(this);panel.add(page3Top=new Button(“Top button”) , “North”);page3Top.addMouseListener(this);panel.add(page3Bottom=new Button(“Bottom button”) ,“South”);page3Bottom.addMouseListener(this);f.

17、add(panel,“panel”);f.setSize(200,200);f.setVisible(true);public void mouseClicked(MouseEvent e) layout.next(f);public void mouseEntered(MouseEvent e)public void mouseExited(MouseEvent e)public void mousePressed(MouseEvent e)public void mouseReleased(MouseEvent e)模拟考题模拟考题Question 31)Which of the foll

18、owing statements are true?1) The default layout manager for an Applet is FlowLayout 2) The default layout manager for a Frame is FlowLayout 3) A layout manager must be assigned to an Applet before the setSize method is called 4) The FlowLayout manager attempts to honor the preferred size of any comp

19、onents模拟考题模拟考题Answer to Question 31)1) The default layout manager for an Applet is FlowLayout 4) The FlowLayout manager attempts to honor the preferred size of any components容器的嵌套import java.awt.*;public class ExGui3private Frame f;private Panel p;private Button bw,bc;private Button bfile,bhelp;publ

20、ic static void main(String args)ExGui3 gui = new ExGui3();gui.go(); public void go()f = new Frame(GUI example 3);bw=new Button(West);bc=new Button(Work space region);f.add(bw,West);f.add(bc,Center);p = new Panel();f.add(p,North);bfile= new Button(File);bhelp= new Button(Help);p.add(bfile);p.add(bhel

21、p);f.pack();f.setVisible(true);n运行结果:nFrameqFrame是一个顶级窗口。qFrame的缺省布局管理器为BorderLayout。nPanelqPanel无法单独显示,必须添加到某个容器中。qPanel的缺省布局管理器为FlowLayout。q当把Panel作为一个组件添加到某个容器中后,该Panel仍然可以有自己的布局管理器。因此,可以利用Panel使得BorderLayout中某个区域显示多个组件。无布局管理器nsetLayout(null)AWT 事件处理机制什么是事件?nEvent事件,就是发生在用户界面上的用户交互行为所产生的一种效果。nEve

22、nt Source产生事件的对象。nEvent handler(Listener)接收事件对象并对其进行处理的方法。事件处理模型nHierachical model(JDK 1.0)事件传递机制。nDelegation model(JDK 1.1, 1.2),授权(委托)处理机制。Delegation Model(事件授权处理模型)n将事件源对象和事件处理器(事件监听器)分开。import java.awt.*;import java.awt.event.*;public class TestButton public static void main(String args)Frame f

23、= new Frame(Test);Button b = new Button(Press Me!);b . a d d A c t i o n L i s t e n e r ( n e w ButtonHandler();f.setLayout(new FlowLayout();f.add(b);f.setSize(200,100);f.setVisible(true); class ButtonHandler implements ActionListener public void actionPerformed(ActionEvent e)System.out.println(Act

24、ion occurred);n使用JDK1.1授权处理模型进行事件处理的一般方法:q对于某种类型的事件XXXEvent,要想接收并处理这类事件,必须定义相应的事件监听器类,该类需要实现针对特定事件的特定接口XXXListener;nActionEventnActionListenerq事件源中产生事件后,必须注册相应于该类事件的监听器,使用addXXXListener(XXXListener )方法来注册监听器。q事件发生后,产生表示特定事件的事件对象,事件对象被传递给已经注册的事件监听器,调用监听器中的特定方法处理事件 事件对象njava.util.EventObject类EventObje

25、ct类是所有事件对象的基础类,所有的事件类都是由它派生出来的。public class EventObject implements java.io.Serializable protected transient Object source; public EventObject(Object source); public Object getSource(); public String toString();java.awt.AWTEvent和AWT有关的所有事件类都由java.awt.AWTEvent类派生 ,它也是EventObject类的子类。AWT事件共有10类,可以归为两大类

26、:低级事件和高级事件。n低级事件qComponentEvent(组件事件:组件尺寸的变化,移动)qContainerEvent(容器事件:组件增加,移动)qWindowEvent(窗口事件:关闭窗口,窗口闭合,图标化)qFocusEvent(焦点事件:焦点的获得和丢失)qKeyEvent(键盘事件:键按下、释放)qMouseEvent(鼠标事件:鼠标单击,移动)n高级事件(语义事件)qActionEvent(动作事件:按钮按下,TextField中按Enter键)qAdjustmentEvent(调节事件:在滚动条上移动滑块以调节数值)qItemEvent(项目事件:选择项目,不选择“项目改变

27、”)qTextEvent(文本事件,文本对象改变)事件监听器n每类事件都有对应的事件监听器n监听器是接口,根据动作来定义方法。interface KeyListener extends java.util.EventListener public void keyPressed(KeyEvent ev);public void keyTeleased(KeyEvent ev);public void keyTyped(KeyEvent ev);注册和注销监听器n注册监听器:public void add(listener);n注销监听器:public void remove(listener)

28、;注册和注销监听器nAWT的组件类中提供注册和注销监听器的方法,例如Button类:(查API)public class Button extends Component .public synchronized void addActionListener(ActionListener l);public synchronized void removeActionListener(ActionListener l);AWT事件及其相应的监听器接口nActionEventq激活组件qActionListenerqActionPerformed(ActionEvent)nItemEventq选

29、择了某些项目qItemListenerqItemStateChanged(ItemEvent)nMouseEventq鼠标移动qMouseListenerqmouseDragged(MouseEvent)mouseMoved(MouseEvent)nMouseEventq鼠标点击等qMouseListenerqmousePressed(MouseEvent) mouseReleased(MouseEvent) mouseEntered(MouseEvent) mouseExited(MouseEvent) mouseClicked(MouseEvent)nKeyEventq键盘输入qKeyLi

30、stenerqKeyPressed(KeyEvent) KeyReleased(KeyEvent) KeyTyped(KeyEvent)nFocusEventq组件收到或失去焦点qFocusListenerqfocusGained(FocusEvent)focusLost(focusEvent)nAdjustementEventq移动了滚动条等组件qAdjustmentListenerqadjustmentValueChanged(AdjustmentEvent)nComponentEventq对象移动缩放显示隐藏等qComponentListenerqcomponentMoved(Compo

31、nentEvent)componentHidden(ComponentEvent)componentResized(ComponentEvent)componentShown(ComponentEvent)nWindowEventq窗口收到窗口级事件qWindowListenerqwindowClosing(WindowEvent)windowOpened(WindowEvent)windowIconified(WindowEvent)windowDeiconified(WindowEvent)windowClosed(WindowEvent)windowActivated(WindowEve

32、nt)windowDeactivated(WindowEvent)nContainerEventq容器中增加删除了组件qContainerListenerqcomponentAdded(containerEvent)componentRemoved(containerEvent)nTextEventq文本字段或文本区发生改变qTextListenerqtextValueChanged(TextEvent)例12.12 import java.awt.*;import java.awt.event.*;public class TwoListen implementsMouseMotionLis

33、tener,MouseListener,WindowListener private Frame f;private TextField tf;public static void main(String args)TwoListen two = new TwoListen();two.go(); public void go() f = new Frame(Two listeners example);f.add(new Label(Click and drag the mouse),North);tf = new TextField(30);f.add(tf,South);f.addMou

34、seMotionListener(this);f.addMouseListener(this);f.addWindowListener(this);f.setSize(300,200);f.setVisible(true);public void mouseDragged (MouseEvent e) S t r i n g s = M o u s e d r a g g i n g : X=+e.getX()+Y = +e.getY();tf.setText(s); public void mouseMoved(MouseEvent e)public void mouseClicked(Mo

35、useEvent e)public void mouseEntered(MouseEvent e)String s = The mouse entered;tf.setText(s); public void mouseExited(MouseEvent e)String s = The mouse has left the building;tf.setText(s);public void mousePressed(MouseEvent e)public void mouseReleased(MouseEvent e) public void windowClosing(WindowEve

36、nt e) System.exit(1);public void windowOpened(WindowEvent e) public void windowIconified(WindowEvent e) public void windowDeiconified(WindowEvent e) public void windowClosed(WindowEvent e) public void windowActivated(WindowEvent e) public void windowDeactivated(WindowEvent e) n可以声明多个接口implements Mou

37、seMotionListener,MouseListener,WindowListenern可以同时监听一个事件源上发生的多种事件:f.addMouseMotionListener(this);f.addMouseListener(this);f.addWindowListener(this);n可以通过事件对象获得详细资料public void mouseDragged(MouseEvent e) String s=“Mouse dragging :X=”+e.getX()+“Y=”+e.getY();tf.setText(s);事件适配器(Event Adapters)n一种简单的实现监听

38、器的手段,缺点是只能单一继承.import java.awt.*;import java.awt.event.*;public class MouseClickHandler extends MouseAdaperpublic void mouseClicked(MouseEvent e) 事件适配器(Event Adapters)nJava.awt.event包中定义的适配器类有:qComponentAdapter(组件适配器)qContainerAdapter(容器适配器)qFocusAdapter(焦点适配器)qKeyAdapter(键盘适配器)qMouseAdapter(鼠标适配器)q

39、MouseMotionAdapter(鼠标运动适配器)qWindowAdapter(窗口适配器)模拟考题模拟考题Question 19)Which of the following are true?1) A component may have only one event listener attached at a time 2) An event listener may be removed from a component 3) The ActionListener interface has no corresponding Adapter class 4) The proces

40、sing of an event listener requires a try/catch block 模拟考题模拟考题Answer to Question 19) 2) An event listener may be removed from a component 3) The ActionListener interface has no corresponding Adapter classAWT 组件库按钮(Button)nButton b = new Button(Quit); nActionEvent事件nActionListener接口ngetActionCommand()

41、nsetActionCommand()复选框 (Checkbox)setLayout(new GridLayout(3,1);add(new Checkbox(“one”,null,true);add(new Checkbox(“two”);add(new Checkbox(“three”);复选框 (Checkbox)nItemEventnItemListenerngetStateChange()获取当前状态ngetItem()获得被修改复选框的字符串对象class Handler implements ItemListener public void itemStateChanged(It

42、emEvent ev)String state = deselected;i f ( e v. g e t S t a t e C h a n g e ( ) = = ItemEvent.SELECTED)state = selected System.out.println(ev.getItem()+ +state);复选框组(CheckboxGroup)n setLayout(new GridLayout(3, 1); CheckboxGroup cbg = new CheckboxGroup(); add(new Checkbox(one, cbg, true); add(new Che

43、ckbox(two, cbg, false); add(new Checkbox(three, cbg, false);下拉式菜单Choice Colorchooser=new Choice();Colorchooser.add(“Green”);Colorchooser.add(“Red”);Colorchooser.add(“Blue”);用ItemListener接口来进行监听Canvasn如创建一个自定义组件,一个应用程序必须继承Canvas类才能获得有用的功能。如果想在画布上完成一些图形处理,则Canvas类中的paint()方法必须被重写。nCanvas组件监听各种鼠标,键盘事件。

44、当在Canvas组件中输入字符时,必须先调用requestFocus()方法。n例12.14import java.awt.*;import java.awt.event.*;import java.util.*;public class MyCanvas implements KeyListener, MouseListener Canvas c;String s=“”;public static void main(String args) Frame f=new Frame(“Canvas”);MyCanvas mc=new Mycanvas();mc.c=new Canvas();f.

45、add(“Center”,mc.c);f.setSize(150,150);mc.c.addMouseListerner(mc);mc.c.addKeyListener(mc);f.setVisible(true);public void mouseClicked(MouseEvent ev)System.out.println(“MouseClicked”);c.requestFocus();public void keyTyped(KeyEvent ev) System.out.println(“KeyTyped”);s+=ev.getKeyChar();c.getGraphics().d

46、rawString(s,0,20); public void keyPressed(KeyEvent ev) System.out.println(“KeyPressed”); public void keyReleased(KeyEvent ev) System.out.println(“KeyReleased”); public void mousePressed(MouseEvent ev) System.out.println(“MousePressed”); public void MouseReleased(MouseEvent ev) System.out.println(“Mo

47、useReleased”); public void mouseEntered(MouseEvent ev) System.out.println(“MouseEntered”); public void mouseExited(MouseEvent ev) System.out.println(“MouseExited”); TextFieldn单行文本输入区n当回车键被按下时,会发生ActionEvent事件,可以通过ActionListener中的actionPerformed()方法对事件进行相应处理。n可以使用setEditable(boolean)方法设置为只读属性。TextFie

48、ldTextField tf1,tf2,tf3,tf4:tf1=new TextField();tf2=new TextField(“”,20); /显示区域为20列tf3=new TextField(“Hello!”);/按文本区域显示tf4=new TextField(“Hello!”,30); /*初始文本为Hello!, 显示区域为30列TextAreanTextArea可以显示多行多列的文本。使用setEditable(boolean)方法,可以将其设置为只读的。在TextArea中可以显示水平或垂直的滚动条。n要判断文本是否输入完毕,可以在TextArea旁边设置一个按钮,通过按钮

49、点击产生的ActionEvent对输入的文本进行处理。列表(List)List lst=new List(4,false);lst.add(“Venus”);lst.add(“Earth”);lst.add(“JavaSoft”);lst.add(“Mars”);cnt.add(lst);Framen顶级窗口,可以显示标题nWindowEvent事件nFrame无法直接监听键盘输入事件。Dialogn是Window类的子类。n对话框和一般窗口的区别在于它依赖于其它窗口。n对话框分为非模式(non-modal)和模式(modal)两种。文件对话框(Filedialog)FileDialog d=

50、new FileDialog(ParentFr,“FileDialog);d.setVisible(true);String filename=d.getFile();菜单n无法直接将菜单添加到容器的某一位置,也无法使用布局管理器对其加以控制。菜单只能被添加到“菜单容器”中。MenuBarn只能被添加到Frame对象中,作为整个菜单树的根基。Frame fr = new Frame(MenuBar);MenuBar mb = new MenuBar();fr.setMenuBar(mb);fr.setSize(150,100); fr.setVisible(true);Menun下拉菜单。它可以被添加到MenuBar中或其它Menu中。Frame fr = ne

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论