Chng 5 Abstract Window Toolkit Swing Objectives Explain

Chương 5: Abstract Window Toolkit Swing

Objectives � Explain Abstract Window Toolkit (AWT) � Explain various Containers and Components �Frame �Panel �Label �Text. Fields and Text. Areas �Checkboxes and Radio. Buttons �Button �Choice � Identify events generated by components � Create a standalone AWT application Java Simplified / Session 22 / 2 of 45

Abstract Window Toolkit - AWT Graphical User Interface (GUI) được dùng để nhận dữ liệu nhập theo một cách thức thân thiện với người dùng Abstract Window Toolkit (AWT) một tập các lớp trong Java cho phép tạo GUI và nhận dữ liệu nhập của người dùng qua chuột và bàn phím AWT cung cấp các item cho phép tạo giao diện hấp dẫn và hiệu quả Java Simplified / Session 6 / 3 of 39 Java Simplified / Session 22 / 3 of 45

Types of GUI Programs Có 2 kiểu chương trình GUI trong Java: ◦ Stand-alone Applications: chạy độc lập ◦ Applets: chạy trên web page GUI dùng các đối tượng (components) để tạo ra tương tác với người dùng Để dùng Components: ◦ import awt (Abstract Windows Toolkits) or ◦ import swing component libraries: là sự mở rộng và cải tiến của AWT Import java. awt. *; Import javax. swing. *; 4 Java Simplified / Session 22 / 4 of 45

Hierarchy of Component classes Component Button Checkbox Container Choice Canvas Label Text. Component Panel Applet Window Frame Text. Area Text. Field Dialog Java Simplified / Session 22 / 5 of 45

Component Component: ◦ Bất cứ gì có thể được đặt vào giao diện và có thể hiển thị hoặc thay đổi kích thước ◦ Một số ví dụ: Textfield, Label, Checkbox, Textarea, Button… Label Text field Checkbox Radio button Text Area Button Java Simplified / Session 22 / 6 of 45

Component class ◦ Cung cấp các phương thức cho nó và ◦ cho các lớp con của nó: Phương thức: ◦ Dimension get. Size() ◦ Void set. Size(int w, int h) ◦ Void set. Size(Dimension p) ◦ Point get. Location() ◦ Void set. Location(int x, int y) ◦ Void set. Location(Point p) ◦… Java Simplified / Session 22 / 7 of 45

Container là một vùng chứa các thành phần Lớp Container trong gói java. awt dẫn xuất ra hai container được sử dụng phổ biến nhất Frame và Panel ◦ Frame là một cửa sổ riêng biệt và có đường viền ◦ Panel là một vùng không có đường viền, chứa trong một cửa sổ Cung cấp hàm add() được nạp chồng để bổ sung một thành phần vào lớp cho trước Java Simplified / Session 22 / 8 of 45

Frame Một cửa sổ độc lập, được sử dụng tạo ra ngững windows cho các giao diện ứng dụng GUI Là lớp con của Window, có thanh tiêu đề, thanh thực đơn, đường viền và các góc có thể thay đổi kích thước Được tạo ra bằng cách dùng các constructor ◦ Frame(): Tạo 1 Frame ẩn không có tiêu đề ◦ Frame(String Title) Tạo 1 Frame ẩn có tiêu đề Title Để giúp Frame hiển thị, sử dụng phương thức ◦ set. Visible() Java Simplified / Session 22 / 9 of 45

Frame Để xây dựng một giao diện ứng dụng cần: Tạo 1 frame: ◦ Ex, Frame Test. Frame = new Frame (“My Test Frame”) Dùng add() để thêm các thành phần GUI khác ◦ Ex, Test. Frame. add(new Button(“OK”) //optional Đặt kích thước cho frame: ◦ Ex, Test. Frame. set. Size(300, 400); // 300 x 400 Đóng gói frame ◦ Test. Frame. pack() //optional Cho hiện thị frame ◦ Test. Frame. set. Visible(true); Java Simplified / Session 22 / 10 of 10 45

Ex: Frame. Demo add. Window. Listener(new import java. awt. *; Window. Adapter() { import java. awt. event. Window. Adapter; public void import java. awt. event. Window. Event; window. Closing(Window. Event we) class Frame. Demo extends Frame { { public Frame. Demo(String title) set. Visible(false); { System. exit(0); super(title); } }); } public static void main (String args[]) { Frame. Demo Obj. Fr = new Frame. Demo(" My Test Frame!!!"); Obj. Fr. set. Size(300, 200); Obj. Fr. add(new Button("OK")); Obj. Fr. set. Visible(true); } } Java Simplified / Session 22 / 11 of 45

Panel Được dùng để nhóm các thành phần lại với nhau Cách đơn giản nhất tạo ra panel là dùng constructor Panel() Vì panel không thể được nhìn thấy trực tiếp, nó phải được thêm vào một Frame Java Simplified / Session 22 / 12 of 45

Ex: Panel. Demo import java. awt. *; class Panel. Demo extends Panel { public static void main(String args[]) { Panel. Demo Obj. Panel = new Panel. Demo(); Frame Obj. Fr = new Frame("Testing a Panel!"); Obj. Fr. add(Obj. Panel); Obj. Fr. set. Size(300, 200); Obj. Fr. set. Visible(true); } public Panel. Demo() { set. Background (Color. magenta); add(new Button("OK")); } } Java Simplified / Session 22 / 13 of 45

Tạo các component của GUI Để sử dụng được các thành phần giao diện đồ họa, cần thực hiện: ◦ Tạo một thành phần GUI bởi 1 constructor thích hợp: Ex: Button btn. OK = new Button(“OK”) ◦ Bổ sung thành phần vừa tạo vào thành phần chứa container (ex, Frame): Ex: add(btn. OK); //this. add(btn. OK) ◦ Nhận và xử lý sự kiện khi chúng xuất hiện: Implement Action. Listener, … Viết code. Java Simplified / Session 22 / 14 of 14 45

Label Chỉ ra mục đích của một item Người dùng không chỉnh sửa được Được tạo ra bằng cách dùng các constructor ◦ Label() Tạo một nhãn không có nội dung ◦ Label(String labeltext) Tạo một nhãn với nội dung là labeltext Java Simplified / Session 22 / 15 of 45

Text. Field Dùng để nhập văn bản Chỉ nhập một dòng Được tạo ra bằng cách dùng các constructor ◦ Text. Field() Tạo một textfield mới ◦ Text. Field(int columns) Tạo một textfield mới có columns cột (layout) ◦ Text. Field(String s) Tạo một textfield mới có nội dung s ◦ Text. Field(String s, int columns) Tạo một textfield mới có nội dung s và columns cột Java Simplified / Session 22 / 16 of 45

Example: Label_Text. Field. Demo import java. awt. *; public class Label_Text. Field. Demo extends Frame { Text. Field txt. Name = new Text. Field(20); Label lbl. Name = new Label("Name : "); public Label_Text. Field. Demo (String title) { super(title); set. Layout(new Flow. Layout()); set. Size(300, 200); add(lbl. Name); add(txt. Name); set. Visible(true); } public static void main(String args[]) { new Label_Text. Field. Demo ("Testing components!"); } } Java Simplified / Session 22 / 17 of 45

Text. Area Được dùng khi văn bản có thể nằm trên nhiều dòng Text. Area được tạo ra bằng cách dùng các constructor ◦ Text. Area() Tạo một textarea mới ◦ Text. Area(int rows, int cols) Tạo một textarea mới với rows dòng và cols cột ◦ Text. Area(String text) Tạo một textarea mới với nội dung text ◦ Text. Area(String text, int rows, int cols) Tạo một textarea mới với nội dung text, rows dòng và cols cột Java Simplified / Session 6 / 18 of 39 Java Simplified / Session 22 / 18 of 45

Example: Text Area import java. awt. *; import java. awt. event. *; class Text. Comments extends Frame { Text. Area txt. Comment = new Text. Area(5, 25); Label lbl. Com = new Label("Comments : "); public Text. Comments(String title) { super(title); set. Layout(new Flow. Layout()); add(lbl. Com); add(txt. Comment); add. Window. Listener(new Window. Adapter() { public void window. Closing(Window. Event we) { set. Visible(false); System. exit(0); } }); } public static void main(String args[]) { Text. Comments Obj. Comment = new Text. Comments("Testing components!"); Obj. Comment. set. Size(200, 200); Obj. Comment. show(); } Java Simplified / Session 6 / 19 of 39 } Java Simplified / Session 22 / 19 of 45

Buttons Cách tốt nhất để ghi nhận các hoạt động của người dùng Được tạo ra bằng cách dùng các constructor ◦ Button() Tạo một button mới ◦ Button(String text) Tạo một button mới với nội dung text Java Simplified / Session 6 / 20 of 39 Java Simplified / Session 22 / 20 of 45

Example Button public class Button. Demo extends Frame{ Button btn. Red = new Button("Red!"); Button btn. Blue = new Button("Blue!"); Button btn. Green = new Button("Green!"); public Button. Demo(String title) { super(title); set. Layout(new Flow. Layout()); public static void main(String add(btn. Red); args[]) { add(btn. Blue); new Button. Demo("The three buttons"); add(btn. Green); } set. Size(300, 200); } set. Visible(true); add. Window. Listener(new Window. Adapter() { public void window. Closing(Window. Event we) { set. Visible(false); System. exit(0); } }); } Java Simplified / Session 6 / 21 of 39 Java Simplified / Session 22 / 21 of 45

Checkbox Dùng để nhận dữ liệu nhiều lựa chọn, người dùng có thể chọn hoặc bỏ chọn bằng cách click vào chúng Được tạo ra bằng cách dùng các constructor ◦ Checkbox() Tạo một checkbox rỗng ◦ Checkbox(String text) Tạo một checkbox với nội dung text ◦ Checkbox(String text, boolean on) Tạo một checkbox với nội dung text và thiết lập trạng thái của checkbox là true hay false thông qua biến on Java Simplified / Session 6 / 22 of 39 Java Simplified / Session 22 / 22 of 45

Example: Checkbox class Checkbox. Demo extends Frame { Checkbox cbox. Read = new Checkbox("Reading", false); Checkbox cbox. Mus = new Checkbox("Music", false); Checkbox cbox. Paint = new Checkbox("Painting", false); add. Window. Listener(new Window. Adapter() { Checkbox cbox. Movie = new Checkbox("Movies", false); public void window. Closing(Window. Event we) { Checkbox cbox. Dance = new Checkbox("Dancing", false); set. Visible(false); Label lbl. Qts = new Label("What's your hobby? " ); System. exit(0); public Checkbox. Demo(String str }){ super(str); }); set. Layout(new Grid. Layout(6, 1)); } set. Size(300, 300); public static void main(String args[]) { add(lbl. Qts); new Checkbox. Demo ("A basket full of checkboxes!"); add(cbox. Read); } add(cbox. Mus); } add(cbox. Paint); add(cbox. Movie); add(cbox. Dance); set. Visible(true); Java Simplified / Session 22 / 23 of 45

Radiobuttons Được dùng làm tuỳ chọn để xác định các chọn lựa Chỉ một thành phần trong group được chọn Trước tiên tạo ra một đối tượng Checkbox. Group ◦ Checkbox. Group cg = new Checkbox. Group(); Sau đó tạo ra từng radio button ◦ Checkbox male = Checkbox(“male”, cg, true); ◦ Checkbox female = Checkbox(“female”, cg, false); Java Simplified / Session 6 / 24 of 39 Java Simplified / Session 22 / 24 of 45

Example: Radio. Button. Demo class Radio. Button. Demo extends Frame { Checkbox. Group cg = new Checkbox. Group(); Checkbox rad. Under = new Checkbox("Undergraduate", cg, false); Checkbox rad. Gra = new Checkbox("Graduate", cg, false); Checkbox rad. Post = new Checkbox("Post Graduate", cg, false); Checkbox rad. Doc = new Checkbox("Doctorate", cg, false); Label lbl. Qts = new Label("What's your primary qualification? " ); public Radio. Button. Demo(String str) { super(str); public static void main(String args[]){ set. Size(250, 300); Radio. Button. Demo Obj = new Radio. Button. Demo set. Layout(new Grid. Layout(6, 1)); ("Literacy!"); add(lbl. Qts); } add(rad. Under); } add(rad. Gra); add(rad. Post); add(rad. Doc); add. Window. Listener(new Window. Adapter(){ public void window. Closing(Window. Event we) { set. Visible(false); System. exit(0); } }); set. Visible(true); Java Simplified / Session 6 / 25 of 39 } Java Simplified / Session 22 / 25 of 45

Lists Hiển thị một danh sách chọn lựa cho người dùng Lớp Choice: tạo ra danh sách nhiều item, ex ◦ Choice Names = new Choice(); Thêm item: dùng phương thức add. Item() ◦ Names. add. Item(“Antonio”); ◦ Names. add. Item(“Leonardo”); Chọn 1 item: dùng get. Selected. Item() ◦ Names. get. Selected. Item()==“Antonio” Java Simplified / Session 6 / 26 of 39 Java Simplified / Session 22 / 26 of 45

Example: List import java. awt. *; add. Window. Listener(new Window. Adapter() import java. awt. event. *; { class Stars extends Frame public void window. Closing(Window. Event we) { { Choice moviestars = new Choice(); set. Visible(false); Label lbl. Qts = new Label("Who is your favorite movie star? "); System. exit(0); public Stars(String str) } { }); super(str); } set. Layout(new Flow. Layout()); public static void main(String args[]) moviestars. add. Item("Antonio Banderas"); { moviestars. add. Item("Leonardo Di. Caprio"); Stars Obj. Star = new Stars ("A sky full of stars!"); moviestars. add. Item("Sandra Bullock"); Obj. Star. set. Size(400, 400); moviestars. add. Item("Hugh Grant"); Obj. Star. show(); moviestars. add. Item("Julia Roberts"); } add(lbl. Qts); } add(moviestars); Java Simplified / Session 6 / 27 of 39 Java Simplified / Session 22 / 27 of 45

Menu Xây dựng hệ thống thực đơn cho chương trình Dùng các lớp Menu. Bar, Menu. Item Abstract class Menu. Component is based class: ◦ ◦ ◦ Menu. Bar class: define menu bar Menu. Item class: define Item in menu bar Menu class: set up pull-down menu in a Item menu Pop. Up. Menu class: display for pop-up menu Checkbox. Menu. Item class: contain items menu checked Java Simplified / Session 22 / 28 of 28 45

Tạo menu Java Simplified / Session 22 / 29 of 29 45

ex Java Simplified / Session 22 / 30 of 30 45

Xử lý sự kiện trong GUI Mô hình xử lý sự kiện Các bước xử lý sự kiện Các lớp sự kiện ◦ Action. Event ◦ Adjustment. Event ◦ Focus. Event ◦ Item. Event ◦ Window. Event ◦ Mouse. Event ◦ Key. Event Java Simplified / Session 22 / 31 of 31 45

Xử lý các sự kiện Các ứng dụng với GUI thường được hướng dẫn bởi các events. Trong Java, các events được thể hiện bằng các đối tượng. Hai nhóm: ◦ Lớp mô tả về ngữ nghĩa của các events ◦ Lớp events ở mức thấp Java Simplified / Session 22 / 32 of 32 45

Các lớp sự kiện trong gói Event Java Simplified / Session 22 / 33 of 33 45

Mô hình xử lý sự kiện 34 Ba thành phần chính của mô hình • Event source: nguồn phát sinh sự kiện, là thành phần của giao diện mà người dùng tác động • Ex: click, move, drag…. • Event object: đối tượng lưu thông tin về sự kiện • lưu trong một đối tượng sự kiện thuộc lớp con của lớp AWT. Event (gói java. awt. event) • Event listener: bộ lắng nghe sự kiện, nhận sự kiện và xử lý • Là cách chương trình có thể xử lý các sự kiện trên các thành phần của giao diện Java Simplified / Session 22 / 34 of 45

Mô hình xử lý sự kiện 35 Java Simplified / Session 22 / 35 of 45

Event Listener Interface Java Simplified / Session 22 / 36 of 36 45

Các lớp sự kiện -> event source Lớp sự kiện Mô tả Action. Event Nhấn một nút, chọn menu, chọn radiobutton Adjustment. Event Di chuyển thanh cuộn Focus. Event Đặt, chuyển focus Item. Event Chọn 1 item trong list, chọn các checkbox Window. Event Đóng, mở, di chuyển cửa sổ Mouse. Event Di chuyển, click, kéo thả chuột Key. Event Nhấn, thả bàn phím Component. Event thay đổi size, di chuyển, bị ẩn hay làm cho hoạt động được Text. Event giá trị trong textfield /textarea thay đổi Java Simplified / Session 22 / 37 of 45

Các bước xử lý sự kiện Những 38 việc cần làm: ◦ Nhúng vào gói event import java. awt. event. *; ◦ Cài đặt giao diện thích hợp với sự kiện muốn xử lý ex, class abc extends Frame implements Action. Listener ◦ Chỉ ra thành phần của giao diện muốn xử lý sự kiện trên đó ex, button 1. add. Action. Listener(this) ◦ Viết hàm xử lý sự kiện tương ứng ex, public void action. Performed(Action. Event x) { } Java Simplified / Session 22 / 38 of 45

Lớp sự kiện Action. Event Lớp: Action. Event Giao diện: Action. Listener Lắng nghe: add. Action. Listener Hàm xử lý: action. Performed 39 Radio. Button Java Simplified / Session 22 / 39 of 45

40 Ví dụ: button Listener Interface Class Action Java Simplified / Session 22 / 40 of 45

Lớp sự kiện Item. Event Lớp: Item. Event Giao diện: Item. Listener Lắng nghe: add. Item. Listener Hàm xử lý: item. State. Changed 41 Java Simplified / Session 22 / 41 of 45

Ví dụ: checkbox 42 Java Simplified / Session 22 / 42 of 45

Lớp sự kiện Mouse. Event Lớp: Mouse. Event Giao diện: Mouse. Listener Lắng nghe: add. Mouse. Listener 43 Hàm xử lý: mouse. Clicked, mouse. Pressed, mouse. Entered, mouse. Exited, mouse. Released Java Simplified / Session 22 / 43 of 45

Mouse. Event & Mouse. Listener is used as a listener for mouse events, an object must implement this Mouse. Listener interface. The Mouse. Listener interface specifies five different instance methods: public void mouse. Pressed(Mouse. Event evt); public void mouse. Released(Mouse. Event evt); public void mouse. Clicked(Mouse. Event evt); public void mouse. Entered(Mouse. Event evt); public void mouse. Exited(Mouse. Event evt); 44 Java Simplified / Session 22 / 44 of 45

45 Ví dụ Java Simplified / Session 22 / 45 of 45

Mouse. Motion. Listener is used as a listener for mouse motion events, an object must implement this Mouse. Motion. Listener interface to handle motion event The interface specifies two different instance methods: public void mouse. Dragged(Mouse. Event evt); public void mouse. Moved(Mouse. Event evt); 46 Java Simplified / Session 22 / 46 of 45

Example : Handle MOuse /* <applet code = Mousey width = 400 height = 400> </applet>*/ import java. awt. *; import java. applet. *; import java. awt. event. *; public class Mousey extends Applet implements Mouse. Listener, Mouse. Motion. Listener { int x 1, y 1, x 2, y 2; public void init() { set. Layout(new Flow. Layout()); set. Bounds(100, 300, 300); add. Mouse. Listener(this); add. Mouse. Motion. Listener(this); this. set. Visible(true); } public void mouse. Clicked(Mouse. Event e) { } public void mouse. Pressed(Mouse. Event e) { x 1 = e. get. X(); y 1 = e. get. Y(); } public void mouse. Moved(Mouse. Event e) {} public void mouse. Released(Mouse. Event e) { x 2 = e. get. X(); y 2 = e. get. Y(); repaint(); } public void mouse. Entered(Mouse. Event e) {} public void mouse. Dragged(Mouse. Event e) {} public void mouse. Exited(Mouse. Event e) {} public void paint(Graphics g) { g. draw. Rect(x 1, y 1, x 2 -x 1, y 2 -y 1); x 2 = 0; y 2 = 0; } } Java Simplified / Session 22 / 47 of 47 45

Example : rect_mouse /* <applet code=Painting width=400 height=400> </applet> */ public void mouse. Pressed(Mouse. Event e) { x 1 = e. get. X(); x 2 = e. get. Y(); } import java. applet. *; public void mouse. Move(Mouse. Event e) import java. awt. *; { import java. awt. event. *; x 3 = e. get. X(); public class Painting extends Applet implements Action. Listener, x 4 = e. get. Y(); Mouse. Listener repaint(); { } Button bdraw = new Button("Draw Rectangle"); public void mouse. Released(Mouse. Event e) int count = 0, x 1, x 2, x 3, x 4; { public void init() x 3 = e. get. X(); { x 4 = e. get. Y(); Border. Layout border = new Border. Layout(); repaint(); set. Layout(border); } add(bdraw, Border. Layout. PAGE_END); public void mouse. Entered(Mouse. Event e) bdraw. add. Action. Listener(this); {} add. Mouse. Listener(this); public void mouse. Exited(Mouse. Event e) this. set. Visible(true); {} } public void mouse. Clicked(Mouse. Event e) {} Java Simplified / Session 22 / 48 of 48 45

Example Contd… public void action. Performed(Action. Event e) { String str = e. get. Action. Command(); if("Draw Rectangle". equals(str)) { count = 1; repaint( ); } } public void paint(Graphics g) { if(count == 1) { g. draw. Rect(x 1, x 2, (x 3 -x 1), (x 4 x 2)); x 3 = x 4 = 0; } } } Java Simplified / Session 22 / 49 of 49 45

Event handling with Components Events are generated whenever a user clicks a mouse, presses or releases a key. Event Delegation Model is used to handle events. This model allows the program to register handlers called ‘listeners’ with objects whose events need to be captured. Handlers are automatically called when an event takes place. Action that has to be done following an event is performed by the respective listener. Java Simplified / Session 6 / 50 of 39 Java Simplified / Session 22 / 50 of 45

Các lớp bố trí và sắp xếp các tp GUI Flow. Layout ◦ Xếp các tp theo hàng/cột từ trái/trên ◦ Mặc định với Panel và Applet Grid. Layout ◦ Xếp trong ô lưới: 1 tp 1 ô Border. Layout ◦ Xếp các thành phần (<5) theo các vị trí: N-S-W-E ◦ Mặc định với Window, Frame, Dialog Grid. Bag. Layout ◦ Xếp các tp vào ô lưới: 1 tp chiếm nhiều ô Java Simplified / Session 22 / 51 of 51 45

Flow. Layout Constructors for the Flow. Layout are : Flow. Layout mylayout = new Flow. Layout(); Flow. Layout ex. Layout = new Flow. Layout(Flow. Layout. LEFT); Ex: set. Layout(new Flow. Layout()); Java Simplified / Session 22 / 52 of 52 45

Border. Layout Manager § Các giá trị hằng cho phép định vị các component trong Border. Layout PAGE_START: đỉnh container LINE_END: bên phải container PAGE_END: đáy container LINE_START: bên trái container LINE_CENTER: giữa container Java Simplified / Session 22 / 53 of 45

Ví dụ: Border. Demo set. Layout(new Border. Layout()); add(best, Border. Layout. LINE_END); add(bwest, Border. Layout. LINE_START); add(bnorth, Border. Layout. PAGE_START); add(bsouth, Border. Layout. PAGE_END); add(bcentre, Border. Layout. CENTER); Java Simplified / Session 22 / 54 of 45

Grid. Layout Manager Chia container thành lưới hình chữ nhật Các component được sắp xếp theo hàng và cột Dùng khi tất cả các component có cùng kích thước Constructor ◦ Grid. Layout g 1= new Grid. Layout(4, 3); Java Simplified / Session 22 / 55 of 45

Grid. Layout Java Simplified / Session 22 / 56 of 45

Grid. Bag. Layout Manager Các component không cần có cùng kích thước Các component được sắp theo hàng và cột Thứ tự đặt các component không phải từ trên xuống hay từ trái qua Một container được thiết lập Grid. Bag. Layout: Grid. Bag. Layout gb = new Grid. Bag. Layout(); Container. Name. set. Layout(gb); Java Simplified / Session 22 / 57 of 45

Grid. Bag. Layout Manager Để dùng layout này, thông tin phải được cung cấp là kích thước và layout của mỗi thành phần Lớp Grid. Bag. Constraints giữ mọi thông tin được yêu cầu bởi lớp Grid. Bag. Layout đến vị trí và kích thước của mỗi component Java Simplified / Session 22 / 58 of 45

Grid. Bag. Layout Manager Danh sách biến đối tượng của lớp Grid. Bag. Constraints ◦ gridx, gridy: vị trí ô đưa component vào (cột, hàng) ◦ gridwidth, gridheight: kích thước của component, chứa mấy ô theo chiều ngang (width) và dọc (height) ◦ Fill: xác định làm thế nào một component lấp đầy ô nếu ô lớn hơn component Grid. Bag. Constraints. NONE giữ nguyên size đối tượng. Grid. Bag. Constraints. VERTICAL giãn chiều cao cho khít Grid. Bag. Constraints. HORIZONTAL giãn chiều ngang của đối tượng cho khít Grid. Bag. Constraints. BOTH giãn cả 2 chiều của đối tượng cho khít Java Simplified / Session 22 / 59 of 45

Grid. Bag. Layout Manager Danh sách biến đối tượng của lớp Grid. Bag. Constraints ◦ ipadx, ipady: tăng kích thước hai bên trái phải (hoặc trên dưới) component thêm ipadx (ipady) pixel khi container thay đổi kích thước ◦ Insets: xác định khoảng trống giữa các component trên đỉnh, đáy, trái và phải ◦ Anchor: neo component vào vị trí nào đó so với ô đặt nó: NORTH, NORTHEAST, NORTHWEST, EAST, SOUTHEAST, SOUTHWEST ◦ weightx, weighty: khoảng cách lớn ra tương đối giữa các đối tượng Java Simplified / Session 22 / 60 of 45

ex import java. awt. *; import java. applet. Applet; public class My. Grid. Bag extends Applet { Text. Area Obj. Ta; Text. Field Obj. Tf; Button butta, buttf; Checkbox. Group cbg; Checkbox cbbold, cbitalic, cbplain, cbboth; Grid. Bag. Layout gb; Grid. Bag. Constraints gbc; public void init() { gb = new Grid. Bag. Layout(); set. Layout(gb); gbc = new Grid. Bag. Constraints(); Obj. Ta = new Text. Area("Textarea ", 5, 10); Obj. Tf = new Text. Field("enter your name"); butta = new Button("Text. Area"); buttf = new Button("Text. Field"); cbg = new Checkbox. Group(); cbbold = new Checkbox("Bold", cbg, false); cbitalic = new Checkbox("Italic", cbg, false); cbplain = new Checkbox("Plain", cbg, false); cbboth = new Checkbox("Bold/Italic", cbg, true); gbc. fill = Grid. Bag. Constraints. BOTH; add. Component(Obj. Ta, 0, 0, 4, 1); gbc. fill = Grid. Bag. Constraints. HORIZONTAL; add. Component(butta, 0, 1, 1, 1); gbc. fill = Grid. Bag. Constraints. HORIZONTAL; add. Component(buttf, 0, 2, 1, 1); gbc. fill = Grid. Bag. Constraints. HORIZONTAL; add. Component(cbbold, 2, 1, 1, 1); gbc. fill = Grid. Bag. Constraints. HORIZONTAL; add. Component(cbitalic, 2, 2, 1, 1); gbc. fill = Grid. Bag. Constraints. HORIZONTAL; add. Component(cbplain, 3, 1, 1, 1); Java Simplified / Session 22 / 61 of 61 45

Ex, cont gbc. fill = Grid. Bag. Constraints. HORIZONTAL; add. Component(cbboth, 3, 2, 1, 1); gbc. fill = Grid. Bag. Constraints. HORIZONTAL; add. Component(Obj. Tf, 4, 0, 1, 3); } public void add. Component(Component comp, int row, int col, int nrow, int ncol) { gbc. gridx = col; gbc. gridy = row; gbc. gridwidth = ncol; gbc. gridheight = nrow; } } gb. set. Constraints(comp, gbc); add(comp); Java Simplified / Session 22 / 62 of 62 45

Using Swing

Introduction Swing is preferable over AWT as more lightweight and is newer. Swing provides some classes support for GUI Java Simplified / Session 22 / 64 of 64 45

Swing components Top-level Container ◦ JFrame (Form Application) ◦ JApplet (Applet) ◦ JDialog Intermediate-level Container ◦ JPanel ◦ JTabbed. Pane ◦ JSplit Atomic components ◦ JLabel, JText. Field, JText. Area, JButton, JCombo. Box, JList, JCheck. Box, JSlider Java Simplified / Session 22 / 65 of 65 45

Simple application import javax. swing. *; public class Frame. App extends JFrame { Frame. App() { super("My Frame"); set. Default. Close. Operation( JFrame. EXIT_ON_CLOSE); set. Visible(true); } public static void main(String[] args) { new Frame. App(); import javax. swing. *; public class Frame. App { public static void main(String[] args) { JFrame w = new JFrame(); w. set. Default. Close. Operation( JFrame. EXIT_ON_CLOSE); w. set. Visible(true); } } Java Simplified / Session 22 / 66 of 66 45

Setting up GUI To create a Java program that uses a GUI, we must: ◦ define and set up the necessary components, ◦ create listener objects and establish the relationship between the listeners and the components which generate the events of interest, and ◦ define what happens as a result of the various user interactions that could occur. Java Simplified / Session 22 / 67 of 67 45

Setting up GUI Create a container and assign a layout manager to it, Create components and add them to the container, Use the container as the content pane of a window or applet. Java Simplified / Session 22 / 68 of 68 45

Detail JFrame JPanel JSlider JTabbed. Pane JOption. Pane (Dialog) JSplit. Pane Java Simplified / Session 22 / 69 of 69 45

Container A basic JFrame has a blank content pane; One can either: ◦ Add things to that pane or ◦ Replace the basic content pane entirely with another container. JPanel is one of fundamental classes in Swing. The basic JPanel is just a blank rectangle. There are two ways to make a useful JPanel: 1. The first is to add other components to the panel; 2. The second is to draw something on the panel. JTabbed. Pane 70 Java Simplified / Session 22 / 70 of 45

Ex: JFrame as a container import java. awt. Flow. Layout; import javax. swing. *; public class content_ex extends JFrame { content_ex(String title){ super(title); JButton a = new JButton("New"); JButton b = new JButton("Save"); set. Layout(new Flow. Layout()); set. Size(200, 300); this. add(a); this. add(b); set. Visible(true); } public static void main(String[] args) { content_ex w = new content_ex("Button Demo"); w. set. Default. Close. Operation( JFrame. EXIT_ON_CLOSE); } Java Simplified / Session 22 / 71 of 71 45

Jpanel as a container Another way of using a JPanel is as a container to hold other components. Java has many classes that define GUI components. Before these components can appear on the screen, they must be added to a container. 72 Java Simplified / Session 22 / 72 of 45

Ex: Jpanel as a container import java. awt. *; import javax. swing. *; class Panel. Demo extends JPanel { public static void main(String args[]){ Panel. Demo Obj. Panel = new Panel. Demo(); JFrame Obj. Fr = new JFrame("Testing a Panel!"); Obj. Fr. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); Obj. Fr. add(Obj. Panel); Obj. Fr. set. Size(400, 400); Obj. Fr. set. Visible(true); } public Panel. Demo() { set. Background (Color. magenta); add(new JLabel("Nhập dữ liệu: ")); add(new JText. Field(20)); add(new JButton("OK ")); } 73 Java Simplified / Session 22 / 73 of 45 }
![Ex: Multi. Panel public class Title. Demo { public static void main (String[] args) Ex: Multi. Panel public class Title. Demo { public static void main (String[] args)](http://slidetodoc.com/presentation_image_h2/6cce734892bd7422e7e033337d0fdce7/image-74.jpg)
Ex: Multi. Panel public class Title. Demo { public static void main (String[] args) { JFrame frame = new JFrame ("Multi Panel"); frame. set. Default. Close. Operation (JFrame. EXIT_ON_CLOSE); JPanel panel = new JPanel(); JPanel p 1 = new JPanel(); p 1. add (new JLabel ("This is Label ")); p 1. add (new JButton ("This is Button ")); panel. add (p 1); JPanel p 2 = new JPanel(); p 2. add (new JCheck. Box ("This is Check. Box")); p 2. add (new JText. Field ("This is Text. Field")); panel. add (p 2); frame. set. Content. Pane(panel); //frame. get. Content. Pane(). add (panel); frame. pack(); frame. show(); } } 74 Java Simplified / Session 22 / 74 of 45

Tabbed pane is a container that allows the user to select (by clicking on a tab) which of several panes are currently visible. A tabbed pane is defined by the JTabbed. Pane class. The add. Tab method creates a tab, specifying the name that appears on the tab and the component to be displayed on that pane when it achieves focus by being “brought to the front” and made visible to the user. Java Simplified / Session 22 / 75 of 75 45

Border mb = Border. Factory. create. Matte. Border (1, 5, 1, 1, Color. yellow); Border b 1 = Border. Factory. create. Line. Border (Color. blue, 2); Border b 2 = Border. Factory. create. Etched. Border (); p 7. set. Border (Border. Factory. create. Compound. Border (b 1, b 2)); Java Simplified / Session 22 / 76 of 76 45

Ex: Tab. Panel. Demo import javax. swing. *; public class Tab. Panel. Demo extends JTabbed. Pane { public static void main (String[] args) { JFrame frame = new JFrame ("Tabbed Panel Demo"); frame. set. Default. Close. Operation (JFrame. EXIT_ON_CLOSE); frame. set. Size(500, 100); Tab. Panel. Demo tp = new Tab. Panel. Demo(); frame. get. Content. Pane(). add(tp); frame. set. Visible(true); } Tab. Panel. Demo(){ add. Tab("Button", new JButton("This is the Button")); add. Tab ("Label", new JLabel("This is the Label")); add. Tab ("Text. Field", new JText. Field("This is the Text. Field" )); add. Tab ("Check. Box", new JCheck. Box("This is the Check. Box")); add. Tab ("Text. Area", new JText. Area("This is the Text. Area")); } } Java Simplified / Session 22 / 77 of 77 45

Split panes A split pane is a container that displays two components separated by a moveable divider bar. Depending on how the split pane is set up, the two components are displayed either side by side or one on top of the other In Java, we create a split pane using the JSplit. Pane class. Java Simplified / Session 22 / 78 of 78 45

Lists The Swing JList class represents a list of items from which the user can choose. In general, all of the options in a list are visible. When the user selects an item using the mouse, it is highlighted. get. Selected. Value: returns the item selected. Event Handling: The List. Selection. Listener interface contains one method called value. Changed. Java Simplified / Session 22 / 79 of 79 45

Ex: List_Split public class List_Split extends Jpanel { private JList list; public static void main (String[] args) { JFrame frame = new JFrame ("List_Split Demo"); frame. set. Default. Close. Operation (JFrame. EXIT_ON_CLOSE); JPanel Pa = new JPanel(); //tp panel phai image. Panel. set. Background (Color. white); List_Split Li = new List_Split (); //tp List ben trai JSplit. Pane sp = new JSplit. Pane(JSplit. Pane. HORIZONTAL_SPLIT, Li, Pa); //2 tp Panel va List sp. set. One. Touch. Expandable (true); frame. get. Content. Pane(). add (sp); frame. pack(); frame. show(); } public List_Split() { String[] file. Names = {"Thin", "Ti", "Ngo", "Mui", "Than", "Dau", "Tuat"}; list = new JList (file. Names); //list. add. List. Selection. Listener (new Listener()); //event handling list. set. Selection. Mode (List. Selection. Model. SINGLE_SELECTION); //chon 1 add (list); } Java Simplified / Session 22 / 80 of 80 45 }

Sliders (Scrollbar) A slider is a component that allows the user to specify a numeric value within a bounded range. A slider can be presented either vertically or horizontally and can have optional tick marks and labels indicating the range of values. The JSlider class has several methods ◦ set. Major. Tick. Spacing: Major tick marks can be set at specific intervals ◦ set. Minor. Tick. Spacing: minor tick marks. ◦ set. Paint. Ticks: Neither is displayed, however, unless the with a parameter of true, is invoked as well. ◦ set. Paint. Labels: Labels indicating the value of the major tick marks are displayed Java Simplified / Session 22 / 81 of 81 45

Slider, ex import java. awt. *; import javax. swing. *; class Slider. Demo extends JFrame { public static void main(String[] args) { JFrame window = new JFrame(); window. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE) ; window. set. Size(300, 200); window. set. Visible(true); JSlider vd. Bar; // vd. Bar = new JSlider(JSlider. HORIZONTAL, 0, 100, 0); vd. Bar. set. Major. Tick. Spacing(10); vd. Bar. set. Minor. Tick. Spacing(2) ; vd. Bar. set. Paint. Ticks(true); vd. Bar. set. Paint. Labels(true); window. set. Layout(new Grid. Layout(2, 1)); window. add(new JLabel("Thang đo: ")) ; JText. Field tx=new JText. Field(10); window. add(tx ) ; window. add(vd. Bar); Java Simplified / Session 22 / 82 of 82 45

Slider, exercise (home) Java Simplified / Session 22 / 83 of 83 45

Dialog box A dialog box is a graphical window that pops up on top of any currently active window so that the user can interact with it. A dialog box can serve a variety of purposes, : ◦ conveying some information, (truyền đạt) ◦ confirming an action, or ◦ Allowing the user to enter some information. Class JOption. Pane : create and use of basic dialog boxes. The basic formats for a JOption. Pane dialog box: ◦ A message dialog simply displays an output string. ◦ A confirm dialog presents the user with a simple Y/N question. ◦ An input dialog presents a prompt and a single input text field into which the user can enter one string of data. Java Simplified / Session 22 / 84 of 84 45

Dialog box - Methods static String show. Input. Dialog (Object msg) Displays a dialog box containg the specified message and an input text field. The contents of the text field are returned. static int show. Confirm. Dialog (Component parent, Object msg) Displays a dialog box containing the specified message and Yes/No button options. If the parent component is null, the box is centered on the screen. static int show. Message. Dialog (Component parent, Object msg) Displays a dialog box containing the specified message. If the parent component is null, the box is centered on the screen. Java Simplified / Session 22 / 85 of 85 45

Dialog Box, ex import javax. swing. JOption. Pane; public class Even. Odd { public static void main (String[] args) { String num. Str, result; int num, again; do { num. Str = JOption. Pane. show. Input. Dialog ("Enter an integer: "); num = Integer. parse. Int(num. Str); result = "That number is " + ((num%2 == 0) ? "even" : "odd"); JOption. Pane. show. Message. Dialog (null, result); again = JOption. Pane. show. Confirm. Dialog (null, "Do Another? "); } while (again == JOption. Pane. YES_OPTION); } } Java Simplified / Session 22 / 86 of 86 45

Layout The way components are added to a container, In Java the technique for laying out components is to use a layout manager. A layout manager is an object to arrange the components in a container; 87 Java Simplified / Session 22 / 87 of 45

Layout Java Simplified / Session 22 / 88 of 88 45

Flow. Layout, ex set. Layout (new Flow. Layout()); set. Background (Color. magenta); 89 Java Simplified / Session 22 / 89 of 45

Box. Layout Box. Layout cho phép add các control theo dòng hoặc cột, tại mỗi vị trí add nó chỉ chấp nhận 1 control, Muốn xuất hiện nhiều control tại một vị trí thì nên add vị trí đó là 1 JPanel rồi sau đó add các control khác vào JPanel này. Box. Layout. X_AXIS: Add các control theo dòng. Box. Layout. Y_AXIS : Add các control theo cột Box. Layout sẽ không tự động xuống dòng khi hết chỗ chứa, tức là các control sẽ bị che khuất nếu như thiếu không gian chứa nó. Java Simplified / Session 22 / 90 of 90 45

Box Layout Java Simplified / Session 22 / 91 of 91 45

Card. Layout Sắp xếp các thành phần giống như các lá bài. Tại mỗi thời điểm chỉ lá bài đầu tiên được hiển thị. Mỗi lá bài thường là một Panel và trên đó có thể dùng bất kỳ một bố cục nào Java Simplified / Session 22 / 92 of 92 45

Border layout A border layout has five areas to which components can be added: North, South, East, West, and Center. The areas have a particular positional relationship to each Java Simplified / Session 22 / 93 of 93 45

A Layout Example Java Simplified / Session 22 / 94 of 94 45

The containment hierarchy tree, ex Java Simplified / Session 22 / 95 of 95 45

Events and Listeners GUIs are largely event-driven; The program waits for events that are generated by the user's actions When an event occurs, the program responds by executing an event-handling method. In order to program the behavior of a GUI, an event-handling methods must be implemented to respond to the events. 96 Java Simplified / Session 22 / 96 of 45

Events and Listeners A listener is an object that includes one or more event-handling methods. The listener, has the responsibility of responding to the event. The event itself is actually represented by a third object, which carries information about the type of event, when it occurred, and so on. 97 Java Simplified / Session 22 / 97 of 45

Ex: Panel. Demo - Action. Listener class Panel. Demo extends JPanel implements Action. Listener { public static void main(String args[]){ Panel. Demo Obj. Panel = new Panel. Demo(); JFrame Obj. Fr = new JFrame("Testing Event Handling!"); Obj. Fr. add(Obj. Panel); Obj. Fr. set. Size(400, 400); Obj. Fr. set. Visible(true); } public Panel. Demo() { JButton bt 1 =new JButton("Input"); JButton bt 2 =new JButton("Exit"); add(bt 1); bt 1. add. Action. Listener(this); add(bt 2); bt 2. add. Action. Listener(this); } public void action. Performed(Action. Event evt) { if (evt. get. Action. Command(). equals("Input")) JOption. Pane. show. Input. Dialog ("Enter a string: "); else if (evt. get. Action. Command(). equals("Exit")) System. exit(0); } 98 } Java Simplified / Session 22 / 98 of 45

Xây dựng lớp sự kiện public class check_exextends JFrame { JLabel saying; JCheck. Box bold, italic; public static void main (String[] args) { check_ex gui = new check_ex(); gui. set. Default. Close. Operation (JFrame. EXIT_ON_CLOSE); gui. pack(); gui. show(); private class Style. Listener implements } public check_ex() { Item. Listener { public (Item. Event e) saying = new JLabel ("Hay doivoid kieuitem. State. Changed chu!!!!"); { saying. set. Font (new Font ("Helvetica", Font. PLAIN, 30)); int style = Font. PLAIN; bold = new JCheck. Box ("Bold"); (bold. is. Selected()) italic = new JCheck. Boxif("Italic"); style = Font. BOLD; Style. Listener listenerif= (italic. is. Selected()) new Style. Listener(); style += Font. ITALIC; bold. add. Item. Listener (listener); italic. add. Item. Listenersaying. set. Font (listener); (new Font ("Helvetica", style, 30)); } add (saying); add (bold); add (italic); set. Layout(new Flow. Layout()); } } } Java Simplified / Session 22 / 99 of 99 45 Checkbox:

Event Radio. Button Ex: Tinh. java Interface: Action. Listener 10 Java Simplified / Session 22 / 100 of 0 45

Canvas – khung vẽ Một thành phần tổng quát để vẽ và thiết kế các thành phần giao diện đồ họa mới. Canvas là một vùng chuyên để vẽ đồ hoạ, nó không bị che bởi các thành phần giao diện khác. Canvas có thể xử lý các sự kiện giống Applet. Để sử dụng Canvas, cần tạo một lớp khác dẫn xuất từ Canvas và cài đặt nạp chồng phương thức paint(). Nên gọi set. Size cho khung vẽ. Toạ độ vẽ là (0, 0) tính trong khung vẽ. 10 Java Simplified / Session 22 / 101 of 1 45

Canvas import java. awt. *; public class My. Canvas extends Canvas { public My. Canvas() { //. . . } public void paint(Graphics g) { /* We override the method here. The graphics * code comes here within the method body. */ } } 10 Java Simplified / Session 22 / 102 of 2 45

Ex, build class vdcanvas // import public class vdcanvas extends Canvas { private int shape; public void paint(Graphics g) { Dimension size = get. Size(); g. set. Color(Color. BLUE); if (shape == 1) g. fill. Rect(40, size. width-80, size. height-80); else if (shape == 2) g. fill. Oval(40, size. width-80, size. height-80); } public void draw(int shape) { this. shape = shape; repaint(); } 10 } Java Simplified / Session 22 / 103 of 3 45

Ex, using vdcanvas class canvas_ex extends JPanel implements Action. Listener { static vdcanvas vd 1 = new vdcanvas(); canvas_ex(){ //khoi tao cac tp button } public static void main(String[] args) { JFrame f = new JFrame("Testing a Canvas!"); canvas_ex w = new canvas_ex(); vd 1. set. Background(Color. light. Gray); f. set. Layout(new Border. Layout()); f. add(w, Border. Layout. NORTH); f. add(vd 1, Border. Layout. CENTER); f. pack(); f. show(); } public void action. Performed(Action. Event event) { if (event. get. Action. Command(). equals("Draw Rectangle")) vd 1. draw(1); else if (event. get. Action. Command(). equals("Draw Circle")) vd 1. draw(2); } 10 } Java Simplified / Session 22 / 104 of 4 45

Setting up Drawing Panel on Frame Paint. Demo public class demo. Two { public static class display. Panel extends JPanel { public display. Panel() { g. set. Color(Color. RED); g. draw. Oval(50, 150, 150); } } public static void main(String[] args) { Jfram-e win = new JFrame("Demo two"); win. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); win. set. Size(400, 300); win. set. Visible(true); display. Panel a. Panel = new display. Panel(); win. set. Content. Pane(a. Panel); } Java Simplified / Session 22 / 105 of 45

Animation. Timer class Timer (int delay, Action. Listener listener) Constructor: Creates a timer that generates an action event at regular intervals, specified by the delay. The event will be handleby the specified listener. void add. Action. Listener (Action. Listener listener) Adds an action listener to the timer. boolean is. Running () Returns true if the timer is running. void set. Delay (int delay) Sets the delay of the timer. void start () Star ts the timer, causing it to generate action events. void stop () Stops the timer, causing it to stop generating action events. 10 Java Simplified / Session 22 / 106 of 6 45

Thiết kế chương trình Các thành phần của chương trình ◦ Dữ liệu của bài toán cần xử lý (Model) ◦ Hiển thị dữ liệu của bài toán thông qua giao diện (View) ◦ Điều khiển tương tác với người dùng (Controller) Ví dụ: Chương trình điều khiển quả bóng ◦ Model: Dữ liệu về quả bóng gồm toạ độ tâm (x, y) và bán kính bóng ◦ View: Giao diện hiển thị dữ liệu quả bóng gồm có hình quả bóng và 2 nút điều khiển ◦ Controller: Điều khiển di chuyển quả bóng Khi ấn nút điều khiển thì quả bóng di chuyển 10 Java Simplified / Session 22 / 107 of 7 45

PP thiết kế chương trình Big Blob Tất cả thành phần Model, View, Controller đặt trong một lớp duy nhất 10 Java Simplified / Session 22 / 108 of 8 45
![ex public class Test. Ball { public static void main(String[] args) { My. Ball. ex public class Test. Ball { public static void main(String[] args) { My. Ball.](http://slidetodoc.com/presentation_image_h2/6cce734892bd7422e7e033337d0fdce7/image-109.jpg)
ex public class Test. Ball { public static void main(String[] args) { My. Ball. Frame my. Frame = new My. Ball. Frame(“Ball Frame”); my. Frame. set. Size(400, 300); my. Frame. set. Visible(true); . . . } } 10 Java Simplified / Session 22 / 109 of 9 45

// No chua ca model, view va controller class My. Ball. Frame extends Frame implements Action. Listener { private int x, y, radius; // du lieu ve qua bong (model) private Button move. Left, move. Right; // thanh phan GUI (view). . . move. Left. add. Action. Listener(this); move. Right. add. Action. Listener(this); . . . // xu ly su kien (controller) public void action. Performed(Action. Event event). . . 11 } 0 Java Simplified / Session 22 / 110 of 45

Example Xử lý với multi checkbox Multi. Check. java Interface: Item. Listener Class: Item. Event Method: Item. State. Change(Item. Event e) Atribute: Item. Event. SELECTED() 11 Java Simplified / Session 22 / 111 of 1 45

EXERCISE Mô tả ◦ ◦ Input: Nhập ngẫu nhiên a, b Clear: xóa trống a, b Exit: Thóa Chọn: Cong, Tru, Nhan, Chia để tính Yêu cầu: ◦ Bố trí GUI hợp lý với panel ◦ Xử lý sự kiện: button, radiobutton Tinh. java 11 Java Simplified / Session 22 / 112 of 2 45
- Slides: 112