Bài giảng Lập trình Java - Chương 4: Lập trình giao diện với Java và Swing

JFrame – Một số phương thức thông dụng public void dispose (); Hủy public Containter getCotentPane() Lấy vùng Content Pane của Frame (Content pane: vùng chứa các đối tượng trong thiết kế giao diện của Swing). Mỗi đối tượng JFrame luôn có 1 ContentPane. getContentPane().add : phương thức thường sử dụng để thêm một đối tượng vào JFrame getContentPane().setBackground(Color c); Thiết lập màu nền cho content pane (frame)

pptx107 trang | Chia sẻ: thanhle95 | Lượt xem: 563 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Bài giảng Lập trình Java - Chương 4: Lập trình giao diện với Java và Swing, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Chương 4: Lập trình giao diện với JAVA & SWINGNội dungGiới thiệu về SwingCác thành phần của Swing:Swing WindowsSwing ControlsSwing ContainersSwing MenuGiới thiệuLà một thư viện để xây dựng các ứng dụng giao diện đồ họa người dùng (GUI – Graphics User Interface) của ngôn ngữ JAVA. Swing toolkit bao gồm một tập hợp các components sử dụng trong việc xây dựng một ứng dụng GUI từ cơ bản đến phức tạp.Swing toolkit có rất nhiều loại control: label, button, checkbox, listbox, tree, table, jframe, SWINGCác thành phần trong Swing toolkit:Swing Windows: Chứa các loại cửa sổ hiển thị của một ứng dụng GUISwing Controls: Các control để thiết kế giao diệnSwing Containers: Các control mà dùng để gom nhóm các control khác.Swing Menu: Thiết kế menu cho một ứng dụng swingSwing Windows: JFrame: Một cửa sổ dạng top-level-windowJDialog: Một cửa sổ hộp thoại sử dụng để nhập và xuất dữ liệuJInternalFrame : Một cửa sổ trong một ứng dụng MDI.Swing Containers: JDesktopPaneJPanelSWING GUI FORMJFrame Hình ảnh:JFrame được sử dụng để làm giao diện chính trong ứng dụng SwingHầu hết các ứng dụng Swing được xây dựng từ JFrameMột JFrame có thể chứa các thành phần khác: button, label, checkbox, Cách sử dụng: Tạo các lớp thừa kế JFrame để thiết kế giao diện cho ứng dụngJFrameKhai báo lớp kế thừa JFrame12345678910111213141516package packageName;import javax.swing.*;public class FrameName extends JFrame {public FrameName() {this.initComponents();}/*** Khởi tạo các thành phần*/private void initComponents() {...pack();}} Khai báo kế thừa JFrame Khai báo sử dụng thư viện SwingHàm khởi tạo các đối tượng giao diện: tạo và thiết lập các thuộc tính cho các control: vị trí, màu sắc, Hàm này tự phát sinh mã nguồn khi sử dụng thiết kế giao diện kéo thả WYSIWYG.Một lớp kế thừa từ JFrame có đủ tất cả các thành phần của JFrame (các thuộc tính / phương thức public / protectedJFrame – Hiển thị12345678910package packageName;public class Main {public static void main(String[] args) {FrameName frm = new FrameName();frm.setVisible(true);}} JFrame – Một số phương thức thông dụngpublic void setDefaultCloseOperation (int operation);Ý nghĩa: Gán phương thức mặc định khi người dùng đóng FrameCó 4 lựa chọn (giá trị int operation)WindowConstants.DO_NOTHING_ON_CLOSE WindowConstants.HIDE_ON_CLOSEWindowConstants.DISPOSE_ON_CLOSEWindowConstants.EXIT_ON_CLOSEJFrame – Một số phương thức thông dụngpublic void setExtendedState (int state);Ý nghĩa: Gán trạng thái của JFrameCó 5 lựa chọn (giá trị int state)JFrame.NORMAL JFrame.ICONIFIED JFrame.MAXIMIZED_HORIZ JFrame.MAXIMIZED_VERT JFrame.MAXIMIZED_BOTHJFrame – Một số phương thức thông dụngpublic void setResizable (boolean resizable);true: Cho phép thay đổi kích thướcfalse: không cho phéppublic void setTitle (String title);Gán tựa đề cho JFramepublic void setIconImage (Image image);Gán hình ảnh Icon cho JFrameJFrame – Một số phương thức thông dụngpublic void setSize (Dimension d);public void setSize (int width, int height);Gán kích thước cho JFramepublic void setLocation (Point p);public void setLocation (int x, int y);Gán vị trí cho JFramepublic void setVisible (boolean visible);true : hiện Jframefalse : ẩn JframeTương tự cho các phương thức get/isJFrame – Một số phương thức thông dụngpublic void dispose ();Hủypublic Containter getCotentPane()Lấy vùng Content Pane của Frame (Content pane: vùng chứa các đối tượng trong thiết kế giao diện của Swing). Mỗi đối tượng JFrame luôn có 1 ContentPane. getContentPane().add : phương thức thường sử dụng để thêm một đối tượng vào JFrame getContentPane().setBackground(Color c); Thiết lập màu nền cho content pane (frame)JFrame – Ví dụ 112345678910111213141516171819package demoswing;import java.awt.Color;import javax.swing.*;public class VD1_Frame extends JFrame { public VD1_Frame() { this.initComponents(); } private void initComponents(){ this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); ImageIcon icon = new ImageIcon(this.getClass().getResource("images/download.png")); this.setIconImage(icon.getImage()); this.setTitle("Ví dụ 1"); this.setLocation(0, 0); this.setSize(300, 400); this.setExtendedState(JFrame.NORMAL); this.getContentPane().setBackground(Color.WHITE); }}Thiết lập icon cho frameJFrame – Ví dụ 1123456789package demoswing;import javax.swing.*;public class DemoSWING {public static void main(String[] args) {JFrame f = new VD1_Frame();f.setVisible(true);}}JFrame – Ví dụ 212345678910111213141516171819package demoswing;import javax.swing.*;public class VD2_Frame extends JFrame { private JButton jbt1; public VD2_Frame() { super(); this.initComponents(); } private void initComponents() { //JFrame this.setTitle("Ví dụ 2"); this.setSize(200, 100); this.setExtendedState(JFrame.NORMAL); //Buton this.jbt1=new JButton(); this.jbt1.setText("Button 1"); this.add(this.jbt1); }}Lưu ý: Khi sử dụng các IDE hỗ trợ lập trình 🡪 Sử dụng tính năng kéo thả các components & IDE sẽ tự động phát sinh mã nguồn tương ứng JDialogJFrame hay JDialog thường sử dụng JDialog nhập liệu hoặc xuất liệuJDialog có 2 trạng tháiModal: Khi Jdialog thực hiện xong mới được phép thao tác lên form cha .Modeless: Sau khi hiển thị dialog, người dùng có thể thao tác lên form chaJDialog thường được sử dụng với trạng thái ModalJDialog - Khai báo lớp kế thừa JDialog1234567891011121314151617package packageName;import javax.swing.*;public class NameDialog extends JDialog {//Dữ liệu + Các phương thức get/set (nếu có)public NameDialog (JFrame parent, boolean modal){super(parent, modal);this.intComponents();}public NameDialog (JDialog parent, boolean modal){super(parent, modal);this.intComponents();}private void initComponents (){}} Khai báo sử dụng thư viện SwingKhai báo kế thừa từ lớp JDialogHàm khởi tạo có thêm tham số là 1 Frame hoặc Dialog chỉ thị cho cửa sổ chaPhương thức initComponents để khởi tạo các thành phần giao diện của dialog.Khai báo dữ liệu và các phương thức get/set để lấy giá trị / truyền giá trị từ form cha.JDialog – Hiển thị JFrame hay JDialog thường sử dụng JDialog nhập liệu hoặc xuất liệuJdialog thường được thiết lập ở trạng thái Modal, nghĩa là khi Jdialog thực hiện xong mới được phép thao tác lên form chaJDialog – Cách sử dụng12345678910111213//JDialog thường được gọi ở một JFrame hoặc JDialog khác//Ví dụ: Gọi hiển thị Dialog và lấy kết quả trả về khi click một buttonprivate void jbuttonActionPerformed(ActionEvent evt){NameDialog dlg=new NameDialog (this, true);//Gán dữ liệu cho dlg thông qua set (nếu có)dlg.setVisible(true);//Lấy dữ liệu cho dlg thông qua get (nếu có)} JDialog – Một số phương thức thông dụngpublic void setDefaultCloseOperation(int operation);Gán phương thức mặc định khi người dùng đóng FrameCó 3 lựa chọn sau:WindowConstants.DO_NOTHING_ON_CLOSE WindowConstants.HIDE_ON_CLOSEWindowConstants.DISPOSE_ON_CLOSEJDialog – Một số phương thức thông dụngMột số phương thức tương tự JFramepublic void setResizable (boolean resizable);public void setTitle (String title);public void setBackground (Color c);public void setForeground (Color c);public void setIconImage (Image image);public void setSize (Dimension d);public void setSize (int width, int height);public void setLocation (Point p);public void setLocation (int x, int y);public void setVisible (boolean visible);public void dispose();public Containter getCotentPane();JDialog – Một số phương thức thông dụngpublic void setModal (boolean modal);true: Modalfalse : ModelessTương tự cho các phương thức get/isJDialog - Ví dụ 3123456789101112131415161718package demoswing;import javax.swing.*;public class VD3_Frame extends JFrame { public VD3_Frame() { initComponents(); } private void initComponents() { ... } private void jbtnOpenDialogActionPerformed (java.awt.event.ActionEvent evt) { VD3_Dialog dlg = new VD3_Dialog(this, true); dlg.setValue(jlblResult.getText()); dlg.setVisible(true); jlblResult.setText(dlg.getValue()); } private JButton jbtnOpenDialog; private JLabel jlblResult;}JDialog - Ví dụ 31234567891011121314151617181920212223package demoswing;import javax.swing.*;public class VD3_Dialog extends JDialog {public VD3_Dialog (JFrame parent, boolean modal) { super(parent, modal); initComponents(); } public String getValue() { return jtxtValue.getText(); } public void setValue(String s) { jtxtValue.setText(s); } private void initComponents() { } private void jbtnOKActionPerformed(java.awt.event.ActionEvent evt) { this.dispose(); } private JLabel jLabel1; private JButton jbtnOK; private JTextField jtxtValue;}Ví dụ 312345678910package demoswing;import javax.swing.*;public class DemoSWING {public static void main(String[] args) { JFrame f = new VD3_Frame(); f.setVisible(true); }}JDesktopPane & JInternalFramejava.lang.Objectjava.awt.Componentjava.awt.Containerjavax.swing.JComponentjavax.swing.JLayeredPanejavax.swing.JDesktopPanejava.lang.Objectjava.awt.Componentjava.awt.Containerjavax.swing.JComponentjavax.swing.JInternalFramejava.lang.Objectjava.awt.Componentjava.awt.Containerjava.awt.Windowjava.awt.Framejavax.swing.JFrameava.lang.Objectjava.awt.Componentjava.awt.Containerjava.awt.Windowjava.awt.Dialogjavax.swing.JDialogjava.lang.Objectjava.awt.Componentjava.awt.Containerjavax.swing.JComponentjavax.swing.JPanelJDesktopPane & JInternalFrameJDesktopPaneJDesktopPane được sử dụng để xây dựng ứng dụng MDIJDesktopPane thường là một thành phần bên trong JFrameJDesktopPane thường được sử dụng để chứa các JInternalFrame bên trongJInternalFrameJInternalFrame được sử dụng để đưa vào bên trong JDesktopPane của JFrame để xây dựng ứng dụng MDI.Các bước xây dựng ứng dụng MDI:Bước 1: Xây dựng một hay nhiều JInternalFrameBước 2: Tạo một JFrame có một JDesktopPane bên trongBước 3: Gắn JInternalFrame vào bên trong JDesktopPaneJDesktopPane và JInternalFrameJFrameJDesktopPaneJDesktopPane & JInternalFrame– Một số phương thức thông dụngJDesktopPane:public void add(Component component);component : thường là JInternalFramepublic JInternalFrame getSelectedFrame();Lấy JInternalFrame đang được chọnpublic JInternalFrame [] getAllFrames();Lấy tất cả các JInternalFrame bên trongJInternalFrameTương tự JFrame12345678910111213141516171819202122232425package demoswing;import javax.swing.*;public class VD4_MDIFrame extends JFrame { public VD4_MDIFrame() { initComponents(); this.setSize(500, 500); JInternalFrame f1 = new JInternalFrame(); f1.setTitle("Form 1"); f1.setSize(200, 200); this.jDesktopPane1.add(f1); f1.setVisible(true); JInternalFrame f2 = new JInternalFrame(); f2.setTitle("Form 2"); f2.setSize(300, 300); this.jDesktopPane1.add(f2); f2.setVisible(true); } private void initComponents() { jDesktopPane1 = new JDesktopPane(); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); getContentPane().add(jDesktopPane1, java.awt.BorderLayout.CENTER); pack(); } private JDesktopPane jDesktopPane1;}Ví dụ 4:JDesktopPane & JInternalFrame – Ví dụ 412345678910package demoswing;import javax.swing.*;public class DemoSWING {public static void main(String[] args) { JFrame f = new VD4_MDIFrame (); f.setVisible(true); }}JPanelJPanel được sử dụng gom nhóm các control bên trong, có thể được sử dụng như một user control.JPanel được sử dụng như một thành phần bên trong JFrame, JDialog, JInternalFrame, hoặc trong một JPanel khác.java.lang.Objectjava.awt.Componentjava.awt.Containerjavax.swing.JComponentjavax.swing.JPanelFlow LayoutBorder LayoutCard LayoutGrid LayoutGrid Bag LayoutBox LayoutGroup LayoutSWING LAYOUT MANAGER:Layout ManagerMột Container là một Component có thể chứa các Component khác như là: JFrame, JDialog, JScollPane, JPanel, JDesktopPane, JInternalFramegetContentPane().add để thêm Component vào ContainerMỗi Container có một đối tượng Layout ManagerLayout Manager là một đối tượng quyết định cách sắp xếp vị trí của các Component bên trong một Container.Các Layout Manager “implements” từ interface LayoutManager hoặc LayoutManger2. Layout ManagerMỗi Container có một đối tượng Layout Manager mặc định, nhưng hoàn toàn có thể gán cho Container một đối tượng Layout Manger theo ý muốn.Mỗi loại Layout Manager có các nguyên tắc riêng cho việc bố trí các Component bên trong một Container.Một Layout Manager chịu trách nhiệm bố trí các Component được thêm vào Container và khi Container thay đổi kích thướcSử dụng phương thức setLayout (LayoutManager mng) của Container để thay đổi cách bố trí các Component bên trong nó.LayoutManagerCác Layout Manager cài đặt từ các interface LayoutManager hoặc LayoutManager2:Layout ManagerImplemented InterfacesFlow LayoutLayoutManager, SerializableBorder LayoutLayoutManager, LayoutManager2, SerializableCard LayoutLayoutManager, LayoutManager2, SerializableGrid LayoutLayoutManager, SerializableGrid Bag LayoutLayoutManager, LayoutManager2, SerializableBox LayoutLayoutManager, LayoutManager2, SerializableGroup LayoutLayoutManager, LayoutManager2FlowLayout Flow Layout bố trí các Component trong Container theo dòng, từ trái sang phải theo thứ tự thêm vào.Tạo dòng mới khi kích thước dòng còn lại không đủ chứa Component thêm vào.Flow Layout bố trí vị trí các Component phụ thuộc vào kích thước của Container.Mỗi dòng của các Component được window mặc định canh giữa theo chiều ngang. Có thể điều chỉnh canh trái hoặc phải.FlowLayout – Một số phương thức phổ biếnpublic FlowLayout (): Phương thức khởi tạo mặc địnhalign: FlowLayout.CENTERvgap: 5px, hgap: 5pxpublic FlowLayout (int align): Phương thức khởi tạo có tham sốalign: canh lềFlowLayout.CENTER : Canh giữaFlowLayout.LEFT; : Canh tráiFlowLayout.RIGHT; : Canh phảihgap: 5px, vgap: 5pxFlowLayout – Một số phương thức phổ biếnpublic FlowLayout(int align, int vgap, int hgap)Phương thức khởi tạo có tham sốalign : canh lềvgap : kích thước chiều nganghgap: chiều dọcCác phương thức get/set :public void setAlignment(int align)public void setHgap(int hgap)public void setVgap (int vgap)public int getAlignment()public int getHgap ()public int getVgap ()12345678910111213141516171819202122232425package demoswing;import java.awt.Dimension;import java.awt.FlowLayout;import javax.swing.JButton;public class VD5_FlowLayoutFrame extends javax.swing.JFrame { public VD5_FlowLayoutFrame() { initComponents(); this.setSize(400, 400); for (int i = 0; i < 20; i ++) { JButton btn = new JButton(); btn.setPreferredSize(new Dimension(70, 30)); btn.setText("Text" + i); this.getContentPane().add(btn); } FlowLayout layout = new FlowLayout(); layout.setAlignment(FlowLayout.LEFT); this.getContentPane().setLayout(layout); } private void initComponents() { setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(null); pack(); }}FlowLayout – Ví dụ 5FlowLayout – Ví dụ 5hGap=5vGap=5hGap=10BorderLayoutBorder Layout bố trí các Component bên trong Container theo 5 vùng:"North", "South", "East", "West" ,"Center“.BorderLayout – Các phương thức thông dụngpublic BorderLayout (): Phương thức khởi tạo mặc địnhhgap = 0vgap = 0public BorderLayout (int hgap, int vgap): Phương thức khởi tạo có tham sốhgap: chiều ngangvgap : chiều dọcpublic void setHgap(int hgap)public void setVgap (int vgap)public int getHgap()public int getVgap ()BorderLayout – Hgap & VgaphGap=20vGap=40123456789101112131415161718192021222324252627import java.awt.BorderLayout;import java.awt.Dimension;import java.awt.FlowLayout;import javax.swing.JButton;public class VD6_BorderLayoutFrame extends javax.swing.JFrame { JButton btnCenter; JButton btnWest; JButton btnEast; JButton btnNorth; JButton btnSouth; public VD6_BorderLayoutFrame() { initComponents(); btnCenter = new JButton("CENTER"); btnWest = new JButton("WEST"); btnEast = new JButton("EAST"); btnNorth = new JButton("NORTH"); btnSouth = new JButton("SOUTH"); btnCenter.setText("CENTER"); this.setSize(400, 300); BorderLayout layout = new BorderLayout(10, 20); this.getContentPane().setLayout(layout); this.getContentPane().add(btnCenter, BorderLayout.CENTER); this.getContentPane().add(btnNorth, BorderLayout.NORTH); this.getContentPane().add(btnSouth, BorderLayout.SOUTH); this.getContentPane().add(btnWest, BorderLayout.WEST); this.getContentPane().add(btnEast, BorderLayout.EAST); }BorderLayout – Ví dụ 6BorderLayout – Ví dụ 628293031323334 private void initComponents() { setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(null); pack(); }}1234567public class DemoSWING { public static void main(String[] args) { JFrame f = new VD6_BorderLayoutFrame(); f.setVisible(true); }}CardLayoutCard Layout quản lý nhiều Card cùng một không gian hiển thịCard Layout giúp quản lý hai hay nhiều Component (thường là JPanel) để chia sẽ cùng một không gian hiển thị.Chỉ duy nhất Top Card được hiển thị.Mỗi “Card” có thể sử dụng Layout Manager riêng.Card nào cũng có thể là Top CardCó thể sử dụng JTabbedPane để thay cho Card LayoutCardLayout – Một số phương thức thông dụngpublic CardLayout (): Phương thức khởi tạo mặc địnhhgap = 0vgap = 0public CardLayout (int hgap, int vgap): Phương thức khởi tạo có tham sốhgap: chiều ngangvgap : chiều dọcpublic void setHgap(int hgap)public void setVgap(int vgap)public int getHgap()public int getVgap()CardLayout – Ví dụ 7this.setLayout(new BorderLayout());this.getContentPane().add(this.jpnchoice, BorderLayout.NORTH);jbtCard1jbtCard2this.jpnchoice.add(this.jbtCard1);this.jpnchoice.add(this.jbtCard2);this.jpnCards = new JPanel();this.jpnCards.setLayout(new CardLayout());this.getContentPane().add(this.jpnCards, BorderLayout.CENTER);CardLayout – Ví dụ 7jbtCard1jbtCard2this.jpnCard1 = new JPanel();this.jpnCard1.setName("Card1");this.jpnCard1.setBackground(Color.WHITE);this.jpnCard1.setLayout(new FlowLayout());this.jpnCards.add(this.jpnCard1,this.jpnCard1.getName());//jbt11this.jbt11 = new JButton("Button 1-1");this.jpnCard1.add(this.jbt11);//jbt12this.jbt12 = new JButton("Button 1-2");this.jpnCard1.add(this.jbt12);jbt11jbtn12CardLayout – Ví dụ 7jbtCard1jbtCard2this.jpnCard2 = new JPanel();this.jpnCard2.setName("Card2");this.jpnCard2.setBackground(Color.WHITE);this.jpnCard2.setLayout(new FlowLayout());this.jpnCards.add(this.jpnCard2,this.jpnCard2.getName());//jbt21this.jbt21 = new JButton("Button 2-1");this.jpnCard1.add(this.jbt11);//jbt22this.jbt22 = new JButton("Button 2-2");this.jpnCard1.add(this.jbt12);jbt21jbtn22123456789101112131415161718192021222324package demoswing;import java.awt.BorderLayout;import java.awt.CardLayout;import java.awt.Color;import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.*;public class VD7_CardLayoutFrame extends javax.swing.JFrame { public VD7_CardLayoutFrame() { initComponents(); this.setSize(300, 120); this.setTitle("CardLayout"); this.setLayout(new BorderLayout()); //jpnChoice this.jpnchoice = new JPanel(); this.jpnchoice.setLayout(new FlowLayout()); this.getContentPane().add(this.jpnchoice, BorderLayout.NORTH); this.jpnchoice.setBackground(Color.BLUE);Ví dụ 7-12526272829303132333435363738394041424344454647 //jbtCard1 this.jbtCard1 = new JButton("Card1"); this.jbtCard1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jbtCard1ActionPerformed(e); } }); this.jpnchoice.add(this.jbtCard1); //jbtCard2 this.jbtCard2 = new JButton("Card2"); this.jbtCard2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jbtCard2ActionPerformed(e); } }); this.jpnchoice.add(this.jbtCard2); //jpnCards this.jpnCards = new JPanel(); this.jpnCards.setLayout(new CardLayout()); this.getContentPane().add(this.jpnCards, BorderLayout.CENTER);Ví dụ 7-24849505152535455565758596061626364656667686970717273//jpnCard1 this.jpnCard1 = new JPanel(); this.jpnCard1.setName("Card1"); this.jpnCard1.setBackground(Color.WHITE); this.jpnCard1.setLayout(new FlowLayout()); this.jpnCards.add(this.jpnCard1,this.jpnCard1.getName()); //jbt11 this.jbt11 = new JButton("Button 1-1"); this.jpnCard1.add(this.jbt11); //jbt12 this.jbt12 = new JButton("Button 1-2"); this.jpnCard1.add(this.jbt12); //jpnCard2 this.jpnCard2 = new JPanel(); this.jpnCard2.setName("Card2"); this.jpnCard2.setBackground(Color.YELLOW); this.jpnCard2.setLayout(new FlowLayout()); this.jpnCards.add(this.jpnCard2,
Tài liệu liên quan