Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java程序设计 JAVA 授课教师:赵小敏 浙江工业大学 软件学院 zxm@zjut.edu.cn.

Similar presentations


Presentation on theme: "Java程序设计 JAVA 授课教师:赵小敏 浙江工业大学 软件学院 zxm@zjut.edu.cn."— Presentation transcript:

1 Java程序设计 JAVA 授课教师:赵小敏 浙江工业大学 软件学院

2 第八章 AWT及AWT事件处理  AWT  AWT事件处理模型  AWT组件类库

3 抽象窗口工具集AWT  Java.awt包包括建立GUI所需基本组件。  Java.awt的主要类及层次关系 Object
BorderLayout Event FlowLayout GridBagLayout MenuComponent MenuBar MenuItem Component Button Container panel window ScrollPane ... Dialog Frame Applet

4 容器(Container) 窗口(Window, Frame) 面板 (Panel) 带滚动的面板(ScrollPane) Applet
组件必须放在容器内才能显示,一个容器可以容纳多个组件,并使他们成为一个整体。 容器本身也是一个组件,具有组件的所有性质,另外,通过add()方法,还具有容纳其它组件的功能, 容器主要包括: 窗口(Window, Frame) 面板 (Panel) 带滚动的面板(ScrollPane) Container panel window ScrollPane Dialog Frame Applet

5 Frame(框架) 带有标题并可改变大小,可以使用add( )方法向Frame中加组件。 import java.awt.*;
public class MyFrame extends Frame{ public static void main(String args[ ]){ MyFrame fr = new MyFrame(“Hello!”); fr.setSize(500,500); fr.setBackground(color.green); fr.setVisible(true); } public MyFrame(String str){ super(str); import java.awt.*; public class MyFrame { public MyFrame(){ Frame fr = new Frame("Hello !"); fr.setSize(200,200); fr.setBackground(Color.green); fr.setVisible(true); } public static void main(String args[ ]){ new MyFrame();

6 Panel(面板)  Panel 不能独立显示,必须放在Window 或Frame中。 是一块无边框的区域。 可以向其中放入基本组件。
fr=new Frame(“Frame with Panel”); Panel pan = new Panel( ); fr.setSize(200,200); fr.setBackground(Color.blue); pan.setSize(100,100); pan.setBackground(Color.yellow); fr.add(pan); fr.setVisible(true); } Frame with Panel

7 创建Panel示例,P213 8-2 import java.awt.*;
public class FrameWithPanel extends Frame { public static void main(String args[ ]){ FrameWithPanel fr = new FrameWithPanel("Hello !"); fr.setSize(200,200); fr.setBackground(Color.blue); fr.setLayout(new GridLayout(2,1)); Panel pan = new Panel(); pan.setSize(200,100); pan.setBackground(Color.yellow); pan.add(new Button("确定")); fr.add(pan); fr.setVisible(true); } public FrameWithPanel(String str){ super(str);

8 Layout Manager(布局管理器)

9 Layout Manager 容器中组件的布局通常由Layout Manager控制。
每个组件的排列顺序、大小和位置。 每个容器都由一个缺省的Layout Manager ,可通过 setLayout( )方法改变。  Java提供的布局管理器: FlowLayout——流式布局 BorderLayout——边界布局 GridLayout——网格布局 CardLayout——卡片布局 GridBagLayout——网格包布局

10 FlowLayout ok ok FlowLayout.LEFT FlowLayout.RIGHT FlowLayout.CENTER
FlowLayout是Panel和Applet的默认布局管理器。 组件按代码添加的顺序,采用从左到右,从上到下逐行摆放。 Flow Layout Open Close ok Flow Layout Open Close ok  setLayout(new FlowLayout(int align,int hgap, int vgap)) FlowLayout.LEFT FlowLayout.RIGHT FlowLayout.CENTER 缺省是居中

11 FlowLayout示例:p215 8-3 import java.awt.*;
public class FlowLayoutWindow extends Frame { public FlowLayoutWindow() { setLayout(new FlowLayout()); add(new Label("Buttons:")); add(new Button("Button 1")); add(new Button("2")); add(new Button("Button 3")); add(new Button("Long-Named Button 4")); add(new Button("Button 5")); } public static void main(String args[]) { FlowLayoutWindow window = new FlowLayoutWindow(); window.setTitle("FlowLayoutWindow Application"); window.pack();//窗口的大小设置为适合组件最佳尺寸与布局所需的空间。 window.show();

12 BorderLayout BorderLayout North West Center East South
BorderLayout是Window、Dialog和Frame的默认布局管理器 Border Layout 分5个区: BorderLayout North West Center East South

13 BorderLayout 构造与安装Border Layout:
setLayout(new BorderLayout( )) -组件间无缝隙 setLayout(new BorderLayout( int hgap, int Vgap)); 加入组件: add(button, BorderLayout.CENTER)

14 BorderLayout示例:p217 8-4 import java.awt.*;
public class BorderLayoutWindow extends Frame { public BorderLayoutWindow() { setLayout(new BorderLayout(10,20)); add(new Button("North"), "North"); add( new Button("South"),"South"); add( new Button("East"),"East"); add( new Button("West"),"West"); add( new Button("Center"),"Center"); } public static void main(String args[]) { BorderLayoutWindow window = new BorderLayoutWindow(); window.setTitle("BorderWindow Application"); window.pack(); window.show();

15 GridLayout 把窗口分成网格,n行*m列。组件从左到右,从上到下填充 构造与安装布局管理器:
setLayout(new GridLayout(int rows, int cols)); setLayout(new GridLayout(int rows, int cols,int hgap,int vgap));

16 GridLayout Manager Grid 2 1 4 3 5 6 例: … f = new Frame(“Grid”) ;
例: … f = new Frame(“Grid”) ; f.setLayout(new Gridlayout(3,2)) ; b1 = new Button(“1”) ; b2 = new Button(“2”); b3 = new Button(“3”); b4 = new Button(“4”); b5 = new Button(“5”); b6 = new Button(“6”); f.add(b1); f.add(b2); f.add(b3); f.add(b4); f.add(b5); f.add(b6); f.pack( ) ; f.setVisible(true) ; Grid 1 2 3 4 5 6

17 CardLayout Manager CardLayout可使两个或更多的组件(一般是Panel)共享同一
显示空间,把组件象一系列卡片一样叠放,一个时刻只能看 到最上面的。 构造方法: CardLayout() CardLayout(int hgap,int vgap) 常用的CardLayout方法有: public void first(Container parent);显示第一张卡片 public void next(Container parent);显示下一张卡片 public void previous(Container parent);显示前一张卡片 public void last(Container parent);显示最后一张卡片 public void show(Container parent,String name);显示指定名称的组件 public void add(String name,Component comp);

18 GridBagLayout GridBagLayout 类是一个灵活的布局管理器,不需要组件的尺寸相同它就可以将组件在垂直方向上和水平方向上对齐。 每个 GridBagLayout 对象保留一个动态的矩形单元网格,每个组件占用一个或多个单元,称为它的显示区域。 每个由一个网格元包布局管理的组件都与一个 GridBagConstraints 的实例相关,它指定了组件在它的显示区域是如何放置的。

19 GridBagLayout 一个 GridBagLayout 对象放置一组组件的方式,取决于与每个组件相关的 GridBagConstraints 对象,并且取决于组件容器的最小尺寸和首选尺寸。 为了有效的使用网格元包布局,必须定制一个或多个与它的组件相关的 GridBagConstraints 对象。通过设置它的实例的一个或多个变量来定制一个 GridBagConstraints 对象

20 GridBagConstraints变量
gridx , gridy 指定组件显示区域左上方的单元,其中最左上角的单元地址为 gridx = 0 ,gridy = 0 。使用 GridBagConstraints.RELATIVE (缺省值)来指定,该组件将被放置在,该组件被添加之前添加到容器中的组件的右边(为 gridx )或下边(为 gridy )。

21 GridBagConstraints变量
gridwidth , gridheight 在组件的显示区域指定在一行中单元的数目(为 gridwidth )或在一列中单元的数目(为 gridheight )。缺省值为 1 。使用 GridBagConstraints.REMAINDER 来指定该组件是在,它所在行(为 gridwidth )或列(为 gridheight )的最后一个。使用 GridBagConstraints.RELATIVE 来指定该组件是在它所在行(为 gridwidth )或列(为   gridheight )的倒数第二个。

22 GridBagConstraints变量
fill 当组件的显示区域大于组件所请求的尺寸时,用来确定是否(和如何)改变组件的大小。可能值为 GridBagConstraints.NONE (缺省), GridBagConstraints.HORIZONTAL (使组件的宽度在水平方向上足够大来填充它的显示区域,但是不改变它的高度), GridBagConstraints.VERTICAL (使组件的高度在垂直方向上足够大来填充它的显示区域,但是不改变它的宽度)和 GridBagConstraints.BOTH (使组件完全填充它的显示区域)。

23 GridBagConstraints变量
ipadx , ipady 指定在布局内组件的内部补空,给组件的最小尺寸添加多少。组件的宽度至少为它的最小宽度加上 (ipadx * 2) 个像素(因为补空应用在组件的两边)。类似地,组件的高度至少为它的最小高度加上 (ipady * 2) 个像素。

24 GridBagConstraints变量
insets 指定组件的外部补空,即在组件和它的显示区域边沿之间间距的最小量。

25 GridBagConstraints变量
anchor 当组件小于它的显示区域时,用来确定在什么位置(显示区域内)放置该组件。有效值为 GridBagConstraints.CENTER (缺省), GridBagConstraints.NORTH , GridBagConstraints.NORTHEAST , GridBagConstraints.EAST , GridBagConstraints.SOUTHEAST , GridBagConstraints.SOUTH , GridBagConstraints.SOUTHWEST , GridBagConstraints.WEST 和 GridBagConstraints.NORTHWEST 。

26 GridBagConstraints变量
weightx , weighty 用来确定如何分布空白区,对于指定改变大小的操作这是十分重要的。如果没有给至少一个组件指定一个权值,行中的权值为 (weightx) ,列中的权值为 (weighty) ,那么所有的组件会都堆在它们容器的中间。这是因为当权值为零时(缺省), GridBagLayout 对象将在它的单元网格和容器边沿之间任意放置额外的空白。

27 GridBagLayout示例:p

28 如何选择布局管理器 GridBagLayout 组件尽量充满容器空间——使用BorderLayout或
组件以自然大小紧凑的在一行中显示——FlowLayout 组件大小相同,并且成行或成列显示——GridLayout

29 GUI布局的例子

30 GUI布局的例子 panel4 panel5 panel1 panel2 panel8 panel3 panel6 panel7

31 GUI的设计步骤 先设计一个窗口,如Frame 确定布局管理器 在窗口中添加所需组件 改变组件颜色、字体 增加事件处理

32 AWT事件处理模型 什么是事件 事件处理机制 事件目录 事件、接口、方法列表 多监听器 事件适配器

33 Event的含义  Events —— 描述所发生事件的对象 Java中有很多不同类型的事件类,用来描述不同 类型的用户动作
事件源 —— 产生事件的组件 事件处理 —— 一个接收事件对象并处理用户交互的方法

34 JDK1.0 与JDK1.1~事件处理机制 在JDK1.0中采用向上传递机制: Frame Panel Button ActionEvent

35 JDK1.1~中的事件处理机制 监听器方式: Panel and Frame Frame event handlers Panel
Button Action event actionPerformed( ActionEvent e){ }

36 JDK1.2中的事件处理机制 监听器:每个事件有一个相应的监听器接口,定义了接收 事件的方法。实现该接口的类,可作为监听器注册。
每个组件都注册有一个或多个监听器(类),该 监听器包含了能接收和处理事件的事件处理。 事件对象只向已注册的监听器报告。

37 JDK1.2中的事件处理机制 包含事件处理的程序应该包括以下三部分内容: 1.在事件处理类的声明中指定要实现的监听器名,如:
public class MyClass implements ActionListener { } 2.实现监听器中的接口,如: public void actionPerformed(ActionEvent e) { ...//响应某个动作的代码... 3.在一个或多个组件上将监听器类的实例注册为监听器,如:someComponent.addActionListener(instanceOfMyClass);

38 按钮事件的示例 主程序: import java.awt.*; public class TestButton{
public static void main(String args[ ]){ Frame f = new Frame(“Test”); Button b = new Button(“Press Me!”); b.addActionListener(new ButtonHandler( )); f.add(b, “Center”); f.pack( ); f.setVisible(true) ; }

39 ButtonHandler.java import java awt.event.* ; public class ButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ System.out.println(“Action occurred”); System.out.println(“Button’s label is:”+ e.getActionCommand()); }

40 关闭窗口按钮事件的示例 import java.awt.*; import java.awt.event.*;
public class MyFrameCanExit extends Frame implements WindowListener { public static void main(String args[ ]){ MyFrameCanExit fr = new MyFrameCanExit("Hello !"); fr.addWindowListener(fr); //注册窗口事件监听器。 fr.setSize(200,200); fr.setBackground(Color.green); fr.setVisible(true); } public MyFrameCanExit(String str){ super(str);

41 关闭窗口按钮事件的示例 public void windowClosing(WindowEvent e) { System.exit(0);
} public void windowClosed(WindowEvent e) { } public void windowOpened(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { }

42 事件分类 java.util.EventObject ActionEvent ContainerEvent AdjustmentEvent
ComponentEvent ItemEvent TextEvent ContainerEvent FocusEvent InputEvent WindowEvent Java.awt.AWTEvent Java.beans.beanContext ...

43 事件监听器接口 事件的监听器。 java.util.EventListener ActionListener … ...
对于AWT每种类型的事件,都定义了相应的事件处理接口; 实现某种监听器接口的类,其对象可作为接收并处理相应 事件的监听器。 java.util.EventListener ActionListener … ... ItemListener

44 事件接口与方法目录 Listener Interface Adapter Class Methods ActionListener 无
actionPerformed AdjustmentListener adjustmentValueChanged ComponentListener ComponentAdapter componentHidden componentMoved componentResized componentShown ContainerListener ContainerAdapter componentAdded componentRemoved FocusListener FocusAdapter focusGained focusLost ItemListener itemStateChanged

45 事件接口与方法目录 Listener Interface Adapter Class Methods KeyListener
KeyAdapter keyPressed keyReleased keyTyped MouseListener MouseAdapter mouseClicked mouseEntered mouseExited mousePressed mouseReleased MouseMotionListener MouseMotionAdapter mouseDragged mouseMoved TextListener textValueChanged WindowListener WindowAdapter windowActivated windowClosed windowClosing windowDeactivated windowDeiconified windowIconified windowOpened

46 监听多个按钮事件 例:编写一个允许学生在文本字段中输入一个数的程序。创建一个每当用户单击一次就将此数加一的按钮。创建另一个每当用户单击一次就将此数减一的按钮。 界面效果如下图所示。

47 import java.awt.*; import java.awt.event.*; class Incrementor2 implements ActionListener{ TextField numberTxf; public void makeGUI(){ Frame frm = new Frame("Incrementor"); frm.setLayout(new FlowLayout()); numberTxf = new TextField("0"); frm.add(numberTxf); Button incrementBtn = new Button("Increment"); frm.add(incrementBtn); incrementBtn.addActionListener(this); Button decrementBtn = new Button("Decrement"); frm.add(decrementBtn); decrementBtn.addActionListener(this); frm.setSize(200,200); frm.show(); }

48 public void actionPerformed(ActionEvent e) {
int oldNum = Integer.parseInt(numberTxf.getText()); int newNum = oldNum; if (e.getActionCommand().equals("Increment")){ //Increment button was pressed newNum++; } else if (e.getActionCommand().equals("Decrement")) { //Decrement button was pressed newNum--; numberTxf.setText(String.valueOf(newNum)); public static void main(String args[]) { Incrementor i = new Incrementor(); i.makeGUI();

49 多监听器 在同一个组件上注册多个监听器,多个监听器可以 监听同一个事件。 根据需要多次调用addXXXListener() 方法注册多个
监听器。

50 Event Adapters  Adapter类实现了相应Listener接口,但所有方法体 都是空的。
便可以只重写需要的方法。 public class MouseClickHandler extends MouseAdapter{ public void mouseClicked(MouseEvent e){ …. }

51 使用内部类进行事件处理 既使用Adaptor类,又避免多重继承的限制。 ——在一个类中定义内部类,由内部类继承相应Adaptor类。 例:
public class MyClass extends Applet { ... someObject.addMouseListener(new MyAdapter()); class MyAdapter extends MouseAdapter { public void mouseClicked(MouseEvent e) { ...//Event handler implementation goes here... }

52 使用内部类进行事件处理 匿名类(Anonymous Class)是没有名字的类。 可以使用匿名内部类进行事件处理。 例1:
public class MyClass extends Applet { ... someObject.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { ...//Event handler implementation goes here... } }); } }

53 AWT组件类库

54 AWT组件类库

55 Component类提供的功能  支持基本的 drawing 。  事件处理。  组件外观控制——字体、颜色  图象处理
paint(), update(), repaint() 方法显示组件自身。  事件处理。 通用的事件处理方法: handleEvent() ;特定的事件处理方法,如 action()  组件外观控制——字体、颜色  图象处理 Canvases以及多数container能够显示图象  屏幕上组件大小与位置控制 preferredSize() , minimumSize()方法可以通知布局管理器组件的 最佳与最小的大小

56 Canvases画布,用来画图的面板

57 Checkbox 与 CheckboxGroup

58 Panel p1, p2; Checkbox cb1, cb2, cb3; //These are independent checkboxes. Checkbox cb4, cb5, cb6; //These checkboxes are part of a group. CheckboxGroup cbg; cb1 = new Checkbox(); //Default state is "off" (false). cb1.setLabel("Checkbox 1"); cb2 = new Checkbox("Checkbox 2"); cb3 = new Checkbox("Checkbox 3"); cb3.setState(true); //Set state to "on" (true).. . . cbg = new CheckboxGroup(); cb4 = new Checkbox("Checkbox 4", cbg, false); //initial state: off (false) cb5 = new Checkbox("Checkbox 5", cbg, false); //initial state: off cb6 = new Checkbox("Checkbox 6", cbg, false); //initial state: off

59 Choice下拉式列表

60 //...Where instance variables are defined:
Choice choice; //pop-up list of choices //...Where initialization occurs: choice = new Choice(); choice.addItem("ichi"); choice.addItem("ni"); choice.addItem("san"); choice.addItem("yon"); label = new Label(); setLabelText(choice.getSelectedIndex(), choice.getSelectedItem()); ...

61 Dialog对话框

62 FileDialog文件对话框

63 List列表

64 ...//Where instance variables are declared:
TextArea output; List spanish, italian; ...//Where initialization occurs: //Build first list, which allows multiple selections. spanish = new List(4, true); //prefer 4 items visible spanish.addItem("uno"); spanish.addItem("dos"); spanish.addItem("tres"); spanish.addItem("cuatro"); spanish.addItem("cinco"); spanish.addItem("seis"); spanish.addItem("siete"); //Build second list, which allows one selection at a time. italian = new List(); //Defaults to none visible, only one selectable italian.addItem("uno"); italian.addItem("due"); italian.addItem("tre"); italian.addItem("quattro"); italian.addItem("cinque"); italian.addItem("sei"); italian.addItem("sette");

65 Menu菜单

66 public class MenuWindow extends Frame {
. . . public MenuWindow() { MenuBar mb; Menu m1, m2, m3, m4, m4_1, m5; MenuItem mi1_1, mi1_2, mi3_1, mi3_2, mi3_3, mi3_4, mi4_1_1, mi5_1, mi5_2; //Add the output displayer to this window... //Build the menu bar. mb = new MenuBar(); setMenuBar(mb); //Build first menu in the menu bar. //Specifying the second argument as true m1 = new Menu("Menu 1", true); mb.add(m1); mi1_1 = new MenuItem("Menu Item 1_1"); m1.add(mi1_1); mi1_2 = new MenuItem("Menu Item 1_2"); m1.add(mi1_2);

67 Scrollbar滚动条

68 ScrollPane带滚动条的面板

69 TextArea and TextField

70 //Where instance variables are defined:
TextField textField; TextArea textArea; public void init() { textField = new TextField(20); textArea = new TextArea(5, 20); textArea.setEditable(false); ...//Add the two components to the panel. }

71 组件颜色与字体的设置 Color类与Font类分别定义了一些颜色、字体, 可以创建新的颜色与字体。
Color c=new Color(r,g,b); Font f=new Font(…);

72 作业 1、实现下面的图形界面

73 作业 2、编写一个用户登录的界面程序,如下图所示。如果用户输入为空,则给出“用户名不可为空”的提示信息,若输入的用户名和密码都是test,则打印“登录成功”,否则打印“用户名不存在或者密码不正确”。

74 作业(第3和4题选做一题) *3、编程实现标准型计算器,如下图所示 标准型计算器

75 作业(第3和4题选做一题) *4、设计一个简单的电话簿功能,用以保存、查看好友的个人信息。好友个人信息包含姓名、性别、出生日期、工作单位、职务、住宅电话、手机号码、办公室电话、 、QQ号码和MSN等信息,将这些信息以对象串行化形式存入文件中。


Download ppt "Java程序设计 JAVA 授课教师:赵小敏 浙江工业大学 软件学院 zxm@zjut.edu.cn."

Similar presentations


Ads by Google