Bài giảng lập trình ứng dụng mạng bài 1 GV võ tấn dũng

86 303 0
Bài giảng lập trình ứng dụng mạng  bài 1   GV  võ tấn dũng

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

TRƯỜNG CAO ĐẲNG CÔNG NGHỆ THÔNG TIN TP.HCM LẬP TRÌNH ỨNG DỤNG MẠNG BÀI GIẢNG VIÊN: VÕ TẤN DŨNG GV: Võ Tấn Dũng JAVA BEANS PHẦN GV: Võ Tấn Dũng JavaBean Overview • Component thành phần độc lập phần mềm lắp ráp với để hình thành ứng dụng Các component Java gọi Bean hay Java-Bean • Các component ứng dụng tương tác với Để tương tác với component phải đặt container Container gọi environment Bản thân container component • Mỗi Bean có thuộc tính (properties) hành vi (behaviors) cho phép Bean tương tác với environment tương tác với Bean khác GV: Võ Tấn Dũng COMPONENT MODEL CÁC KHÁI NIỆM TRONG BEAN Introspection (khám phá nội quan) Properties (các thuộc tính) Customization (sự tùy biến) Events (các kiện) Persistence (bảo tồn) Methods (các phương thức) GV: Võ Tấn Dũng • • • • • • PHẦN GV: Võ Tấn Dũng Bean’s properties THUỘC TÍNH CỦA BEAN (PROPERTIES) GV: Võ Tấn Dũng • Thuộc tính cho biết trạng thái (state) đối tượng Các thuộc tính truy cập tên thuộc tính • Người dùng tương tác với bean thông qua thuộc tính Bằng cách thay đổi thuộc tính, nhà phát triển ứng dụng đem đến cho component diện mạo hành vi khác • Thuộc tính bean thay đổi dòng lệnh code công cụ trực quan (visual tools) • Thuộc tính thật biến nằm lớp • Thông thường biến dùng vào hai mục đích gán liệu vào lấy liệu • Giá trị thuộc tính không nên truy cập trực tiếp mà cần phải thông qua phương thức • Các phương thức để đọc liệu từ biến gọi getter Các phương thức để gán liệu cho biến gọi setter • Các thuộc tính có tính chất sau: read-and-write, read-only, write-only • Kiểu liệu thuộc tính kiểu sơ cấp (primitive) int, long, boolean,…hoặc kiểu liệu đối tượng lớp (kiểu wrapper class) GV: Võ Tấn Dũng CÁC GETTER VÀ SETTER CÁC GETTER VÀ SETTER • Các setter getter nên theo mẫu thiết kế (design pattern) sau đây: – public void set( value); – public get(); • Nếu có kiểu boolean getter theo mẫu sau: – public boolean is(); • Ví dụ: GV: Võ Tấn Dũng – Xem trang 51,52/”Developing Java Bean”-Robert Englander – Xem mục 3.2 chương 9/”Java-tập 1”-Phương Lan Indexed properties • Các phần tử mảng truy xuất nhờ vào số thuộc tính kiểu mảng gọi thuộc tính số (indexed properties) • Các mẫu thiết kế (design pattern): – Setter: • public [] get(); • public void set([] value); – Getter: • public get(int index); • public void set(int index, value); – private Color[] standardColor={Color.white,Color.green,Color.red}; – public int getStandardColor(int idx); – public int setStandardColor(int idx, Color c); GV: Võ Tấn Dũng • Ví dụ: Bound properties 10 GV: Võ Tấn Dũng • Khi thuộc tính bean có thay đổi giá trị, báo cho bean khác biết thay đổi cách thông báo • Các thuộc tính có hỗ trợ thông báo gọi bound properties (thuộc tính thể thay đổi) • Hoạt động thực thông qua Event Listener import java.awt.*; import java.awt.event.*; import java.beans.*; import java.io.*; import javax.swing.*; public class PersistentFrameTest { public static void main(String[] args) { chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); PersistentFrameTest test = new PersistentFrameTest(); test.init(); } public void init() { frame = new JFrame(); frame.setLayout(new FlowLayout()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("PersistentFrameTest"); frame.setSize(400, 200); JButton loadButton = new JButton("Load"); frame.add(loadButton); 30 loadButton.addActionListener(EventHandler.create(ActionListener.class, this,"load")); JButton saveButton = new JButton("Save"); frame.add(saveButton); saveButton.addActionListener(EventHandler.create(ActionListener.class, this,"save")); frame.setVisible(true); } 72 GV: Võ Tấn Dũng Ví dụ: PersistentFrameTest.java public void load() { // show file chooser dialog int r = chooser.showOpenDialog(null); // if file selected, open if(r == JFileChooser.APPROVE_OPTION) { try { File file = chooser.getSelectedFile(); XMLDecoder decoder = new XMLDecoder(new FileInputStream(file)); JFrame newFrame = (JFrame) decoder.readObject(); decoder.close(); } catch (IOException e) { JOptionPane.showMessageDialog(null, e); } } } 73 GV: Võ Tấn Dũng Ví dụ: PersistentFrameTest.java public void save() { // show file chooser dialog int r = chooser.showSaveDialog(null); // if file selected, save if(r == JFileChooser.APPROVE_OPTION) { try { File file = chooser.getSelectedFile(); XMLEncoder encoder = new XMLEncoder(new FileOutputStream(file)); encoder.writeObject(frame); encoder.close(); } catch (IOException e) { JOptionPane.showMessageDialog(null, e); } } } private static JFileChooser chooser; private JFrame frame; } 74 GV: Võ Tấn Dũng Ví dụ: PersistentFrameTest.java PHẦN 75 GV: Võ Tấn Dũng Property Editor & Customizers • Một khía cạnh quan lập trình trực quan cho phép ta hiệu chỉnh thuộc tính hành vi component mà không cần phải viết code để hiệu chỉnh • Hình thức phổ biến cho việc tạo property sheet để dùng cho việc thiết lập giá trị thuộc tính cho component • Như vậy, bên cạnh việc viết code cho lớp Bean, ta phải thực giao diện PropertyEditor để xây dựng soạn thảo thuộc tính cho Bean (tức tạo property sheet) • Các thuộc tính Color, String, Boolean,…(các basic type) có property editors ngầm định 76 GV: Võ Tấn Dũng Khái niệm Property Editor CÁC BƯỚC XÂY DỰNG PROPERTY EDITORS 77 GV: Võ Tấn Dũng • Tiến trình xây dựng property editor sau: – Tạo Bean Infor Class tương ứng với Bean – Triển khai code cho method getPropertyDescriptors – Phương thức trả mảng đối tượng PropertyDescriptor objects Ta phải xây dựng đối tượng tương ứng với property trình bày property editor Chart Bean Example • Hãy xem Example 8-4 (chapter 8) ChartBean.java sách Core Java™ Volume II - Advanced Features, Seventh EditionBy Cay S Horstmann, Gary Cornell • Chart Bean example 8-4 có thuộc tính sau: Color property: graphColor String property: title int property: titlePosition double[] property: values boolean property: inverse 78 GV: Võ Tấn Dũng – – – – – package com.horstmann.corejava; import java.beans.*; /*The bean info for the chart bean, specifying the property editors.*/ public class ChartBeanBeanInfo extends SimpleBeanInfo { public PropertyDescriptor[] getPropertyDescriptors() { try { PropertyDescriptor titlePositionDescriptor = new PropertyDescriptor("titlePosition", ChartBean.class); titlePositionDescriptor.setPropertyEditorClass(TitlePositionEditor.class); PropertyDescriptor inverseDescriptor = new PropertyDescriptor("inverse", ChartBean.class); inverseDescriptor.setPropertyEditorClass(InverseEditor.class); PropertyDescriptor valuesDescriptor= new PropertyDescriptor("values", ChartBean.class); valuesDescriptor.setPropertyEditorClass(DoubleArrayEditor.class); return new PropertyDescriptor[] { new PropertyDescriptor("title", ChartBean.class), titlePositionDescriptor, valuesDescriptor, new PropertyDescriptor("graphColor", ChartBean.class), inverseDescriptor }; } catch (IntrospectionException e){ e.printStackTrace(); return null;} } } 79 GV: Võ Tấn Dũng ChartBeanBeanInfo.java Viết Property editor • Để viết Property editor, ta cần thực interface PropertyEditor lớp PropertyEditorSupport • Ví dụ, để bắt đầu viết editor cho thuộc tính vị trí tiêu đề (title) Chart Bean ta làm sau: // property editor class for title position class TitlePositionEditor extends PropertyEditorSupport • Property Editor simple editor chỉnh sửa thuộc tính text, choice, giao diện GUI Property Editor dùng để chỉnh sửa thuộc tính đơn, thuộc tính mảng, vân… vân… 80 GV: Võ Tấn Dũng { } Simple property editor • Simple property editor làm việc chuỗi văn thông qua hai hàm setAsText getAsText • Ví dụ: xét thuộc tính titlePosition Chart Bean Với đoạn code này, nhập vị trí cho title Chart Bean ta phải nhập vào chuỗi: “Left”, “Center”, “Right” 81 GV: Võ Tấn Dũng – private static final int LEFT = 0; – private static final int CENTER = 1; – private static final int RIGHT = 2; class TitlePositionEditor extends PropertyEditorSupport { public String getAsText() { int value = (Integer) getValue(); return options[value]; } public void setAsText(String s) { for (int i = 0; i < options.length; i++) { if (options[i].equals(s)) { setValue(i); return; } } } private String[] options = { "Left", "Center", "Right" }; } Simple property editor 82 GV: Võ Tấn Dũng • Nếu nhập “Left”,”Center”,“Right” tay ta nhập bị sai người dùng nhập vào chuỗi May mắn lớp PropertyEditorSupport có hỗ trợ phương thức đơn giản cho phép chọn giá trị thuộc tính theo dạng Choice Đó phương thức getTags, trả mảng chuỗi package com.horstmann.corejava; import java.beans.*; /*A custom editor for the titlePosition property of the ChartBean The editor lets the user choose between Left, Center, and Right */ public class TitlePositionEditor extends PropertyEditorSupport { public String[] getTags() { return options; } private String[] options = { "Left", "Center", "Right" }; public String getJavaInitializationString() { return "" + getValue(); } public String getAsText() { int value = (Integer) getValue(); return options[value]; } public void setAsText(String s) { for (int i = 0; i < options.length; i++) { if (options[i].equals(s)) {setValue(i);return;} } } 83 } GV: Võ Tấn Dũng TitlePositionEditor.java Một số cách khác để tạo Editor Property • GUI-Based Property Editors • The custom editor dialog box for editing an array 84 GV: Võ Tấn Dũng (Xem Chapter sách “Core Java™ Volume II Advanced Features, Seventh Edition” By Cay S Horstmann, Gary Cornell) Customizers • Bên cạnh việc Property Editor để chỉnh sửa giá trị property Bean, tạo Customizer editor để chỉnh sửa thuộc tính Khi nhấp phải vào Bean (lúc sử dụng Bean để thiết kế chương trình) Customizer xuất Xem thêm cách viết ví dụ Chapter sách “Core Java™ Volume II Advanced Features, Seventh Edition” By Cay S Horstmann, Gary Cornell 85 GV: Võ Tấn Dũng • 86 GV: Võ Tấn Dũng HẾT BÀI SỐ [...]... mọi đối tượng Listener đã đăng ký để Listener xử lý sự kiện bằng hàm propertyChange của Listener 13 GV: Võ Tấn Dũng – public void propertyChange(PropertyChangeEvent evt) VÍ DỤ: về Bound properties 14 GV: Võ Tấn Dũng • Ví dụ 9 -1 và 9-2 chương 9/”Java-tập 1 -Phương Lan Constrained properties 15 GV: Võ Tấn Dũng • Hạn chế của các bound properties là các listener phải chấp nhận giá trị thuộc tính đã thay... throws IntrospectionException 26 GV: Võ Tấn Dũng • Design pattern 3: BeanInfo Class (Property Descriptor) 27 GV: Võ Tấn Dũng • Các vị dụ về Property Descriptor: Xem trang 15 6 ,15 7 ,15 8/”Developing Java Bean”-Robert Englander Indexed Property Descriptor • Cú pháp: – public IndexedPropertyDescriptor(String propertyName, Class beanClass) throws IntrospectionException 28 GV: Võ Tấn Dũng • Ví dụ: public PropertyDescriptor[... hủy bỏ quá trình thay đổi giá trị cho thuộc tính • Đối tượng VetoableChangeSupport cũng tương tự như PropertyChangeSupport dùng để quản lý các đối tượng listener PropertyChangeSupport được dùng cho bound property còn VetoableChangeSupport dùng 17 cho constrained property GV: Võ Tấn Dũng – public void vetoableChange(PropertyChangeEvent evt) VÍ DỤ: về Constrained properties 18 GV: Võ Tấn Dũng • Ví dụ... phát triển trực quan (visual development tool) vào lúc design-time • Có hai cách để thực hiện tiến trình này: 20 GV: Võ Tấn Dũng – Cơ chế phản ánh mức thấp (low-level reflection mechanism) Hay còn được gọi là Introspector ngầm định – Xây dựng BeanInfo class bên cạnh một Bean BeanInfo Class 21 GV: Võ Tấn Dũng • Trong một số trường hợp, ta muốn phơi bày những thuộc tính, sự kiện, phương thức của một Bean... properties 11 GV: Võ Tấn Dũng • Một PropertyChangeEvent của một bounded property chỉ được thông báo ra bên ngoài khi nó có sự thay đổi Tức là sự kiện (event) về sự thay đổi đó đã xảy ra • Nếu một bean có bound property thì nó phải cung cấp một hàm đăng ký (register) và một hàm gỡ bỏ đăng ký (unregister) tương ứng với một bộ lắng nghe sự kiện thuộc tính (PropertyChangeListener) • Người lập trình có thể... GV: Võ Tấn Dũng • Ví dụ 9-3 và 9-4 chương 9/”Java-tập 1 -Phương Lan PHẦN 3 Introspection 19 GV: Võ Tấn Dũng (khám phá nội quan) KHÁI NIỆM INTROSPECTION • Introspection là tiến trình phơi bày các thuộc tính (properties), các phương thức (methods), các sự kiện (events) mà một Bean có thể hỗ trợ • Tiến trình này được dùng vào lúc run-time của chương trình hoặc bởi các công cụ phát triển trực quan (visual... (SecurityException e) { return null; } catch (NoSuchMethodException e) { return null; } } 31 GV: Võ Tấn Dũng Method Descriptor Event Set Descriptor – public EventSetDescriptor( Class sourceClass, String eventSetName, Class listenerType, String listenerMethodName ) throws IntrospectionException 32 GV: Võ Tấn Dũng • Event Set Descriptor phơi bày các sự kiện có thể sinh ra bởi một Bean Nhiều event khác... Method removeListenerMethod ) throws IntrospectionException 33 GV: Võ Tấn Dũng – public EventSetDescriptor( Class sourceClass, String eventSetName, Class listenerType, String listenerMethodNames[], String addListenerMethodName, String removeListenerMethodName )throws IntrospectionException Event Set Descriptor • Ví dụ 1: 34 GV: Võ Tấn Dũng public EventSetDescriptor[] getEventSetDescriptors() { try... là Thermostat được hiện thực bởi lớp Thermostat.class Ta xây dựng Bean Descriptor cho nó như sau: 23 GV: Võ Tấn Dũng – BeanDesciptor bd = new BeanDescriptor(BeansBook.Simulator.Thermostat.class); BeanInfo Class (Bean Descriptor) • Ví dụ: package BeansBook.Simulator; import java.beans.*; 24 GV: Võ Tấn Dũng public class ThermostatBeanInfo extends SimpleBeanInfo { public BeanDescriptor getBeanDescriptor()... indexedGetter, Method indexedSetter )throws IntrospectionException 29 GV: Võ Tấn Dũng Các dạng cú pháp khác: Method Descriptor • Method được phơi bày một cách đơn giản bằng cách thêm tiền tố public trước tên phương thức Method Descriptor cho phép ta chỉ định một cách tường minh rằng method nào của một Bean sẵn có để được gọi • Cú pháp: 30 GV: Võ Tấn Dũng – public MethodDescriptor(Method method) – public MethodDescriptor( ... Listener 13 GV: Võ Tấn Dũng – public void propertyChange(PropertyChangeEvent evt) VÍ DỤ: Bound properties 14 GV: Võ Tấn Dũng • Ví dụ 9 -1 9-2 chương 9/”Java-tập 1 -Phương Lan Constrained properties 15 ... Persistence (bảo tồn) Methods (các phương thức) GV: Võ Tấn Dũng • • • • • • PHẦN GV: Võ Tấn Dũng Bean’s properties THUỘC TÍNH CỦA BEAN (PROPERTIES) GV: Võ Tấn Dũng • Thuộc tính cho biết trạng thái (state)... dùng 17 cho constrained property GV: Võ Tấn Dũng – public void vetoableChange(PropertyChangeEvent evt) VÍ DỤ: Constrained properties 18 GV: Võ Tấn Dũng • Ví dụ 9-3 9-4 chương 9/”Java-tập 1 -Phương

Ngày đăng: 04/12/2015, 17:49

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan