Bài giảng Lập trình hướng đối tượng - Chương 5: Lập trình giao diện với Java - Trần Minh Thái

Tóm tắt Bài giảng Lập trình hướng đối tượng - Chương 5: Lập trình giao diện với Java - Trần Minh Thái: ...c void windowClosing(WindowEvent e) { System.exit(0); } public static void main(String []args) { ViDuVeFrame vd = new ViDuVeFrame(); vd.setVisible(true); } }java.awt.PanelĐược dùng để tạo ra các giao diện theo ý muốn (nhóm các component lại với nhau)Một giao diện có thể có nhiều panel sắp xếp...ae.getSource() == myButton) { //Định nghĩa xử cho sự kiện nhấn nút } } public static void main(String[] args) { ViDuButton vd = new ViDuButton(); vd.setVisible(true); } } java.awt.Text FieldText Field (ô văn bản) cho phép nhận dữ liệu từ bàn phím trên một dòngMột số phương thứcTextField(...);...box); }Ví dụ Checkboxpublic static void main(String []args) { ViDuCheckBox vd = new ViDuCheckBox(); vd.setVisible(true); } @Override public void itemStateChanged(ItemEvent e) { //Định nghĩa xử lý sự kiện chọn } }Radio ButtonCác Checkbox có thể được đặt trong một CheckboxGroup để tạo ra các ...

pptx97 trang | Chia sẻ: havih72 | Lượt xem: 335 | Lượt tải: 0download
Nội dung tài liệu Bài giảng Lập trình hướng đối tượng - Chương 5: Lập trình giao diện với Java - Trần Minh Thái, để tải tài liệu về máy bạn click vào nút DOWNLOAD ở trên
 Chương 5 Lập trình giao diện với JavaTRẦN MINH THÁIEmail: minhthai@huflit.edu.vnWebsite: www.minhthai.edu.vn Cập nhật: 02 tháng 07 năm 2016Nội dungGiới thiệu về lập trình giao diện	Nguyên lý xử lý sự kiện trong JavaCác thành phần giao diện cơ bản trong AWTTổ chức giao diện với Layout ManagerLập trình AppletLập trình ứng dụng với SWINGGiới thiệu về lập trình giao diệnTập hợp các lớp java cung cấp hỗ trợ thiết kế, xây dựng GUI (Graphic User Interface) bao gồm 2 thư viện: awt (java.awt.*): lớp cơ bản lập trình GUI, được phát triển bởi IBM swing (javax.swing.*): dễ dàng và mềm dẻo hơn trong lập trình GUIGiới thiệu AWTAWT viết tắt của Abstract Windowing ToolkitAWT là tập hợp các lớp Java cho phép chúng ta tạo một GUI.Cung cấp các mục khác nhau để tạo hoạt động và hiệu ứng GUIimport java.awt.*;import java.awt.event.*;Giới thiệu AWTjava.awt gồm các lớp GUI cơ bản Các lớp Container – lớp chứa (Frame, Panel, Dialog, ScollPanel)Các lớp Component (như Button, TextComponent, Label)Các lớp quản lý layout(FlowLayout, BorderLayout, GridLayout) Các lớp đồ họa tùy biến(Graphics, Color, Font) Giới thiệu AWTjava.awt.event gồm các lớp xử lý sự kiện trên giao diện Các lớp sự kiện (ActionEvent, MouseEvent, KeyEvent và WindowEvent) Các giao diện nghe sự kiện(MouseListener, KeyListener...) Các lớp Adapter (MouseAdapter, KeyAdapter)Nguyên tắc xây dựng GUILựa chọn một container: Frame, Window, Dialog, Applet, Tạo các control: (buttons, text areas, list, choice, checkbox,...)Đưa các control vào vùng chứaSắp xếp các control trong vùng chứa (Layout)Thêm các xử lý sự kiện (Listeners)Container và Component Container: chứa các component, có thể vẽ và tô màu Bản thân container cũng là một componentMột container có thể chứa các container khácPhương thức add(Component): thêm một component vào containerComponent: là đối tượng cơ bản tạo nên giao diệnCho phép người dùng tương tác với chương trìnhVí dụToạ độscreenMyWindowheightscreen heightyxwidthscreen widthTop-level ContainerFrameDialogAppletTop-level ContainerFrame: cửa sổ chính của giao diện chương trìnhXây dựng cửa sổ chương trình bằng cách kế thừa lớp Frame hoặc kết tập 1 đối tượng FrameKế thừa để sử dụng ngay các thành viên của FrameDialog: cửa sổ pop-up được sử dụng để tạo ra các tương tác nằm ngoài cửa sổ chínhApplet: sử dụng trên xây dựng chương trình chạy trên trình duyệt WebSecondary ContainersPanel: khung chữ nhật nằm trong một top-level container, được sử dụng để tạo layout cho chương trìnhScrollPane: tạo ra hiệu ứng cuộn chuột (ngang/dọc) cho một componentXử lý sự kiệnNgười dùng tương tác với chương trình qua giao diệnChương trình phải nghe được các sự kiện trên giao diện để thực hiện hành động tương ứng Ví dụ: nhập liệu, nhấn phím Enter, nhấp chuột, đóng cửa sổ, ... Xử lý sự kiệnTham gia sự kiện: nguồn (source) sinh sự kiện, bộ nghe sự kiện (listener), và sự kiện (event)Nguồn (source): component phát sinh sự kiện(button, textfield...)Mỗi nguồn sẽ đăng ký các bộ nghe sự kiện khác nhauKhi có sự kiện nào đó xảy ra từ nguồn, phương thức xử lý sự kiện (event handler) trên bộ nghe sự kiện sẽ được gọi để xử lýXử lý sự kiệnWindowListenerpublic interface WindowListener{public void windowClosing(WindowEvent evt);public void windowOpened(WindowEvent evt);public void windowClosed(WindowEvent evt);public void windowActivated(WindowEvent evt);public void windowDeactivated(WindowEvent evt);public void windowIconified(WindowEvent evt);public void windowDeiconified(WindowEvent evt);}MouseListenerpublic interface MouseListener {public void mousePressed(MouseEvent evt);public void mouseReleased(MouseEvent evt);public void mouseClicked(MouseEvent evt);public void mouseEntered(MouseEvent evt);public void mouseExited(MouseEvent evt);}KeyListenerpublic interface KeyListener {public void keyPressed(KeyEvent evt);public void keyReleased(KeyEvent evt);public void keyTyped(MouseEvent evt);}Xử lý sự kiệnPhương thức xử lý sự kiệnpublic void actionPerformed(Lớp sự kiện) {}Xác định nguồn phát sinh sự kiệnKiểu component tên đối tượng.getSource()java.awt.FrameFrame được dùng để xây dựng các ứng dụng GUI chạy độc lậpFrame là một cửa sổ có thanh tiêu đề và các đường biên. Bố cục mặc định của Frame là BorderLayoutjava.awt.FrameFrame kế thừa từ Window, nó có thể nghe các sự kiện xảy ra trên cửa sổ khi cài đặt giao tiếp WindowListenerCác ứng dụng độc lập thường tạo ra cửa sổ kế thừa từ lớp Frameimport java.awt.Frame;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;public class ViDuVeFrame extends Frame 	implements WindowListener{ public ViDuVeFrame(){ super("Vi du ve Frame"); this.setSize(300, 200); this.addWindowListener(this); } @Override public void windowClosing(WindowEvent e) { System.exit(0); } public static void main(String []args) { ViDuVeFrame vd = new ViDuVeFrame(); vd.setVisible(true); }}java.awt.PanelĐược dùng để tạo ra các giao diện theo ý muốn (nhóm các component lại với nhau)Một giao diện có thể có nhiều panel sắp xếp theo một layout nhất định, mỗi panel lại có các component sắp xếp theo một layout riêngPanel có bố cục mặc định là FlowLayoutjava.awt.PanelButtonTextField12 ButtonPanel(GridLayout)Panel(BorderLayout)Frame(BorderLayout)Ví dụ Panelimport java.awt.*;public class ViDuPanel extends Frame { Panel myPanel; public ViDuPanel(){ super("Vi du Frame co chua Panel"); this.setSize(300, 200); myPanel=new Panel(); this.add(myPanel); } public static void main(String []args){ ViDuPanel vd = new ViDuPanel(); vd.setVisible(true); }}java.awt.DialogLà một cửa sổ, thường dùng để nhập hoặc hiển thị thông tin với người dung, bố cục mặc định là BorderLayoutHai loại hộp thoạiModal: Phải đóng hộp thoại trước khi chuyển sang cửa sổ khácModaless: Có thể giữ nguyên hộp thoại và chuyển sang cửa sổ khácJava.awt.Dialogimport java.awt.*;public class ViDuDialog extends Frame { public ViDuDialog(){ super("Vi du Frame co chua Dialog"); this.setSize(300, 200); Dialog dialog = new Dialog(this, "Vi du Dialog“	, false); dialog.setSize(200, 100); dialog.setVisible(true); } public static void main(String []args){ ViDuDialog vd= new ViDuDialog(); vd.setVisible(true); }}Thêm đối tượng componentKhai báo đối tượng component cần thêmKhởi tạo đối tượng với các phương thức khởi tạo phù hợpXác định container chứa component nàySử dụng phương thức add (aComponent) để thêm component vào containerjava.awt.LabelLabel dùng để trình bày một chuỗi văn bản ra màn hìnhMột số phương thức của Label:public Label(); // tạo nhãnpublic Label(String s); // tạo nhãn với nội dung spublic Label(String s, int align); // tạo và canh lề void setText(String s); // đặt nội dung nhãnvoid setAlignment(int align); // canh lề nhãn...Ví dụ Labelimport java.awt.Frame;import java.awt.Label;public class ViDuLabel { public static void main(String []args) { Frame myFrame = new Frame("Frame co chua Label"); myFrame.setSize(300, 200); Label myLabel = new Label(); myLabel.setText(“Day la Label"); myLabel.setAlignment(Label.CENTER); myFrame.add(myLabel); myFrame.setVisible(true); }}java.awt.ButtonMột số phương thức của ButtonButton(); // tạo nút nhấnButton(String s); // tạo nút nhấn có tên svoid setLabel(String s); // đổi tên nútString getLabel(); // lấy tên nút nhấnĐể lắng nghe sự kiện nhấn nút ta cần cài đặt giao tiếp ActionListenerVí dụ Buttonimport java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class ViDuButton extends Frame 	implements ActionListener { Button myButton; public ViDuButton() { super("Frame co chua Button"); this.setSize(300, 200); myButton = new Button("Button"); myButton.setSize(50, 10); this.add(myButton); this.setVisible(true); myButton.addActionListener(this); }Ví dụ Buttonpublic void actionPerformed(ActionEvent ae) { if (ae.getSource() == myButton) { //Định nghĩa xử cho sự kiện nhấn nút } } public static void main(String[] args) { ViDuButton vd = new ViDuButton(); vd.setVisible(true); }}java.awt.Text FieldText Field (ô văn bản) cho phép nhận dữ liệu từ bàn phím trên một dòngMột số phương thứcTextField(...); // khởi tạovoid setEditable(boolean b); // đặt/tắt chế độ nhậpvoid setEchoChar(char c); // đặt kí tự hiển thịĐối tượng nghe cần cài đặt 2 giao tiếpActionListenerTextListenerCài đặt phương thức textValueChanged();Ví dụ Text Fieldimport java.awt.Frame;import java.awt.TextField;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.TextEvent;import java.awt.event.TextListener;public class ViDuTextField extends Frame 	implements ActionListener, TextListener { TextField myTextField; public ViDuTextField(){ super("Frame co Text Field"); this.setSize(300, 200); myTextField = new TextField(30); this.add(myTextField); myTextField.addTextListener(this); myTextField.addActionListener(this); }Ví dụ Text Fieldpublic static void main(String []args) { ViDuTextField vd = new ViDuTextField(); vd.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { //Định nghĩa xử lý cho sự kiện } @Override public void textValueChanged(TextEvent e) { //Định nghĩa xử lý cho sự kiện }}java.awt.ChoiceChoice cung cấp khả năng lựa chọn một trong số các mục trong danh sách sổ xuốngMột số phương thứcChoice(); // khởi tạovoid addItem(String s); // thêm item là sString getItem(int index);// lấy item có chỉ số indexString getSeclectedItem(); // trả về item được chọnint getSelectedIndex(); // trả về index của item được chọnLớp nghe cài đặt giao tiếp ItemListenerCài đặt phương thức itemStateChanged(...)Ví dụ Choiceimport java.awt.Choice;import java.awt.Frame;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;public class ViDuChoice extends Frame 	implements ItemListener { Choice myChoice; public ViDuChoice() { super("Frame co lua chon"); this.setSize(300, 200); myChoice = new Choice(); myChoice.addItem("Item1"); myChoice.addItem("Item2"); myChoice.addItem("Item3"); myChoice.addItemListener(this); this.add(myChoice); }Ví dụ Choicepublic static void main(String[] args) { ViDuChoice vd = new ViDuChoice(); vd.setVisible(true); } @Override public void itemStateChanged(ItemEvent e) { //Xử lý sự kiện chọn item }}java.awt.CheckboxCheckbox cung cấp các hộp tuỳ chọn cho người dùng đánh dấuMột số phương thứcCheckbox(...); // khởi tạovoid setLabel(Strings); // đặt nhãn mớibooleangetState(); // lấy trạng thái hiện tạiLớp nghe cài đặt giao tiếp ItemListenerCài đặt phương thức itemStateChanged(...)Ví dụ Checkboximport java.awt.Checkbox;import java.awt.Frame;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;public class ViDuCheckBox extends Frame 	implements ItemListener{ Checkbox myCheckbox; public ViDuCheckBox(){ super("Frame co Checkbox"); this.setSize(300, 200); myCheckbox = new Checkbox("Danh dau chon"); myCheckbox.addItemListener(this); this.add(myCheckbox); }Ví dụ Checkboxpublic static void main(String []args) { ViDuCheckBox vd = new ViDuCheckBox(); vd.setVisible(true); } @Override public void itemStateChanged(ItemEvent e) { //Định nghĩa xử lý sự kiện chọn }}Radio ButtonCác Checkbox có thể được đặt trong một CheckboxGroup để tạo ra các Radio ButtonChỉ cho phép chọn 1 tuỳ chọn trong nhómimport java.awt.*;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;public class ViDuRadioButton extends Frame 	implements ItemListener { CheckboxGroup myGroup; Checkbox myRadio1; Checkbox myRadio2; public ViDuRadioButton() { super("Frame co Radio button"); this.setSize(300, 200); this.myGroup = new CheckboxGroup(); this.myRadio1 = new Checkbox("Nam",myGroup, true); this.myRadio2 = new Checkbox("Nu",myGroup, false); this.add(myRadio1); this.add(myRadio2); myRadio1.addItemListener(this); myRadio2.addItemListener(this); this.setLayout(new GridLayout(1, 2)); }public static void main(String[] args) { ViDuRadioButton vd = new ViDuRadioButton(); vd.setVisible(true); } @Override public void itemStateChanged(ItemEvent e) { //Định nghĩa xử lý thay đổi lựa chọn }}java.awt.ListList cho phép người dùng chọn một hay nhiều item từ một danh sách các itemMột số phương thứcList(); // khởi tạoList(int items, boolean ms); // cấu tử mở rộngString getSeclectedItem(); // lấy lại thành phần được chọnLớp nghe cài đặt giao tiếp ItemListener và/hoặc ActionListenerVí dụ Listimport java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;public class ViDuList extends Frame 	implements ItemListener, ActionListener { List myList; public ViDuList(){ super("Frame co chua list"); this.setSize(300, 200); myList = new List(3); myList.add("List 1"); myList.add("List 2"); myList.add("List 3"); this.add(myList); myList.addItemListener(this); myList.addActionListener(this); }Ví dụ List @Override public void actionPerformed(ActionEvent e) { // Xử lý sự kiện } @Override public void itemStateChanged(ItemEvent e) { // Xử lý sự kiện } public static void main(String []args){ ViDuList vd=new ViDuList(); vd.setVisible(true); }}Trình bày component (Layout)Flow LayoutBorder LayoutGrid LayoutGridbag LayoutNull LayoutFlowLayoutCác component được sắp xếp theo thứ tự từ trái sang phải và từ trên xuống dướiCác component có kích thước tuỳ chỉnhNếu chiều rộng của Container không đủ chỗ cho các component thì tự động tạo ra một dòng mới	Thường được dùng để sắp xếp các button trong 1 PanelCó thể điều chỉnh khoảng cách giữa các componentVí dụimport java.awt.*;public class ViDuFlowLayout extends Frame { Button[] myButton; public ViDuFlowLayout() { super("Vi du FlowLayout"); this.setSize(300, 200); this.setLayout(new FlowLayout(FlowLayout.CENTER, 	20, 10));//Canh giữa, cách ngang 20, dọc 10 myButton = new Button[10]; for (int i = 0; i 	 Ví dụimport java.applet.Applet;import java.awt.*;public class MyFirstApplet extends Applet{ public void paint(Graphics g){ g.drawString("Hello, this is my first 	Java Applet", 25, 50); }}  Ví dụ về Java AppletMyFirstApplet.javaMyFirstApplet.htmlCác phương thức của GraphicsdrawString(string, left, bottom): Vẽ một xâu với font chữ và màu hiện tại với góc trái (left) và đáy (bottom) của xâudrawRect(left, top, width, height): Vẽ đường viền hình chữ nhật (1-pixel border) với màu hiện tạifillRect(left, top, width, height): Vẽ hình chữ nhật đặc với màu hiện tạidrawLine(x1, y1, x2, y2): Vẽ một đường với độ dày 1 pixel từ tọa độ (x1, y1) đến tọa độ (x2, y2) Các phương thức của Graphics (tt)drawOval, fillOval: Vẽ hình oval (viền/đặc) với các tham số chỉ ra là hình chữ nhật bao quanhdrawPolygon, fillPolygon: Vẽ hình đa giác (viền/đặc) với các điểm được xác định bởi các mảng hoặc một đối tượng Polygon drawPolyline: Vẽ đường gấp khúcdrawImage: Vẽ hình ảnh (JPEG hoặc GIF) Các phương thức của Graphics (tt)drawArc: Vẽ đường viền hình cungfillArc: Vẽ hình cung đặcColor getColor(): Lấy màu hiện tạisetColor(Color): Đặt màuFont getFont(): Lấy thông tin fontsetFont(Font f): Gán thông tin mới cho font import java.applet.Applet;import java.awt.*;public class ViDuGraphics 	extends Applet { public void paint(Graphics g){	g.setFont(new Font("Tahoma“	, Font.BOLD, 20)); g.setColor(Color.BLUE); g.drawString("Ví dụ đối 	 tượng Graphics", 15, 20); g.setColor(Color.RED);	g.drawLine(15, 30, 215, 30);	g.drawRect(15, 40, 200, 50); 	g.fillOval(15, 40, 200, 50);	int x[]={15, 40, 100, 170};	int y[]={100, 140, 150, 250};	g.drawPolygon(x, y, 4); }}Java SwingQ&A

File đính kèm:

  • pptxbai_giang_lap_trinh_huong_doi_tuong_chuong_5_lap_trinh_giao.pptx