Bài giảng Lập trình Java - Chương 4: Lập trình giao diện với JAVA & SWING
Nội dung
Giới thiệu về Swing
Các thành phần của Swing:
Swing Windows
Swing Controls
Swing Containers
Swing Menu
Bạn đang xem 20 trang mẫu của 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 & SWING", để tải tài liệu gốc về máy hãy click vào nút Download ở trên
Tóm tắt nội dung 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 & SWING
Chương 4 : Lập trình giao diện với JAVA & SWING
Nội dung
Giới thiệu về Swing
Các thành phần của Swing:
Swing Windows
Swing Controls
Swing Containers
Swing Menu
Giới thiệu
Là 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,
SWING
Cá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 GUI
Swing Controls : Các control để thiết kế giao diện
Swing 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 swing
Swing Windows:
JFrame: Một cửa sổ dạng top-level-window
JDialog: Một cửa sổ hộp thoại sử dụng để nhập và xuất dữ liệu
JInternalFrame : Một cửa sổ trong một ứng dụng MDI.
Swing Containers:
JDesktopPane
JPanel
SWING GUI FORM
JFrame
Hình ảnh:
JFrame được sử dụng để làm giao diện chính trong ứng dụng Swing
Hầu hết các ứng dụng Swing được xây dựng từ JFrame
Mộ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ụng
JFrame
Khai báo lớp kế thừa JFrame
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package 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 Swing
Hà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 / protected
JFrame – Hiển thị
1
2
3
4
5
6
7
8
9
10
package 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ụng
public void setDefaultCloseOperation ( int operation);
Ý nghĩa : Gán phương thức mặc định khi người dùng đóng Frame
Có 4 lựa chọn (giá trị int operation)
WindowConstants. DO_NOTHING_ON_CLOSE
WindowConstants. HIDE_ON_CLOSE
WindowConstants. DISPOSE_ON_CLOSE
WindowConstants. EXIT_ON_CLOSE
JFrame – Một số phương thức thông dụng
public void setExtendedState ( int state);
Ý nghĩa : Gán trạng thái của JFrame
Có 5 lựa chọn (giá trị int state)
JFrame. NORMAL
JFrame. ICONIFIED
JFrame. MAXIMIZED_HORIZ
JFrame. MAXIMIZED_VERT
JFrame. MAXIMIZED_BOTH
JFrame – Một số phương thức thông dụng
public void setResizable ( boolean resizable);
true: Cho phép thay đổi kích thước
false: không cho phép
public void setTitle ( String title);
Gán tựa đề cho JFrame
public void setIconImage ( Image image);
Gán hình ảnh Icon cho JFrame
JFrame – Một số phương thức thông dụng
public void setSize ( Dimension d);
public void setSize ( int width, int height);
Gán kích thước cho JFrame
public void setLocation ( Point p);
public void setLocation ( int x, int y);
Gán vị trí cho JFrame
public void setVisible ( boolean visible);
true : hiện Jframe
false : ẩn Jframe
Tương tự cho các phương thức get / is
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)
JFrame – Ví dụ 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package 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 frame
JFrame – Ví dụ 1
1
2
3
4
5
6
7
8
9
package demoswing;
import javax.swing.*;
public class DemoSWING {
public static void main( String [] args) {
JFrame f = new VD1_Frame ();
f. setVisible ( true );
}
}
JFrame – Ví dụ 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package 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
JDialog
JFrame hay JDialog thường sử dụng JDialog nhập liệu hoặc xuất liệu
JDialog có 2 trạng thái
Modal : 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 cha
JDialog thường được sử dụng với trạng thái Modal
JDialog - Khai báo lớp kế thừa JDialog
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package 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 Swing
Khai báo kế thừa từ lớp JDialog
Hàm khởi tạo có thêm tham số là 1 Frame hoặc Dialog chỉ thị cho cửa sổ cha
Phươ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ệu
Jdialog 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 cha
JDialog – Cách sử dụng
1
2
3
4
5
6
7
8
9
10
11
12
13
//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 button
private 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ụng
public void setDefaultCloseOperation (int operation);
Gán phương thức mặc định khi người dùng đóng Frame
Có 3 lựa chọn sau:
WindowConstants. DO_NOTHING_ON_CLOSE
WindowConstants. HIDE_ON_CLOSE
WindowConstants. DISPOSE_ON_CLOSE
JDialog – Một số phương thức thông dụng
Một số phương thức tương tự JFrame
public 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ụng
public void setModal ( boolean modal);
true: Modal
false : Modeless
Tương tự cho các phương thức get/is
JDialog - Ví dụ 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package 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ụ 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package 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ụ 3
1
2
3
4
5
6
7
8
9
10
package demoswing;
import javax.swing.*;
public class DemoSWING {
public static void main( String [] args) {
JFrame f = new VD3_Frame ();
f.setVisible(true);
}
}
JDesktopPane & JInternalFrame
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JLayeredPane
javax.swing. JDesktopPane
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing. JInternalFrame
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing. JFrame
ava.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Dialog
javax.swing .JDialog
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing. JPanel
JDesktopPane & JInternalFrame
JDesktopPane
JDesktopPane được sử dụng để xây dựng ứng dụng MDI
JDesktopPane thường là một thành phần bên trong JFrame
JDesktopPane thường được sử dụng để chứa các JInternalFrame bên trong
JInternalFrame
JInternalFrame đượ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 JInternalFrame
Bước 2: Tạo một JFrame có một JDesktopPane bên trong
Bước 3: Gắn JInternalFrame vào bên trong JDesktopPane
JDesktopPane và JInternalFrame
JFrame
JDesktopPane
JDesktopPane & JInternalFrame– Một số phương thức thông dụng
JDesktopPane :
public void add ( Component component);
component : thường là JInternalFrame
public JInternalFrame getSelectedFrame ();
Lấy JInternalFrame đang được chọn
public JInternalFrame [] getAllFrames ();
Lấy tất cả các JInternalFrame bên trong
JInternalFrame
Tương tự JFrame
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package 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ụ 4
1
2
3
4
5
6
7
8
9
10
package demoswing;
import javax.swing.*;
public class DemoSWING {
public static void main(String[] args) {
JFrame f = new VD4_MDIFrame ();
f.setVisible(true);
}
}
JPanel
JPanel đượ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.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing. JPanel
Flow Layout
Border Layout
Card Layout
Grid Layout
Grid Bag Layout
Box Layout
Group Layout
SWING LAYOUT MANAGER:
Layout Manager
Một Container là một Component có thể chứa các Component khác như là: JFrame , JDialog , JScollPane , JPanel , JDesktopPane , JInternalFrame
getContentPane().add để thêm Component vào Container
Mỗi Container có một đối tượng Layout Manager
Layout 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 Manager
Mỗ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ước
Sử 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ó.
LayoutManager
Các Layout Manager cài đặt từ các interface LayoutManager hoặc LayoutManager2:
Layout Manager
Implemented Interfaces
Flow Layout
LayoutManager , Serializable
Border Layout
LayoutManager , LayoutManager2 , Serializable
Card Layout
LayoutManager , LayoutManager2 , Serializable
Grid Layout
LayoutManager , Serializable
Grid Bag Layout
LayoutManager , LayoutManager2 , Serializable
Box Layout
LayoutManager , LayoutManager2 , Serializable
Group Layout
LayoutManager , LayoutManager2
FlowLayout
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.
FlowLayou ...
NONE, HORIZONTAL, VERTICAL, BOTH
anchor:
BoxLayout
Box Layout bố trí các Component bên trong Container theo 1 dòng theo trục X, hoặc là trục Y.
BoxLayout(Container container, int align)
container: chứa các Component
axis:
BoxLayout.X_AXIS : Trục X
BoxLayout.Y_AXIS : Trục Y
GroupLayout (Free Design)
Group Layout bố trí các Component bên trong Container theo chiều ngang và chiều dọc.
Sự bố trí được thực hiện theo mỗi chiều riêng lẽ
JLabel
JButton
JTextField
JCheckBox
JRadioButton
JPanel
BASIC SWING COMPONENTS:
JComboBox, JList
JTable
JMenu
JToolBar
JOptionPane
JFileChooser
JLabel
Methods:
setText (String text)
getText ()
setSize (Dimenstion d)
setForeground (Color fg)
Events:
mouseClicked
JButton
Methods:
setText ( String text)
getText ()
setForeground ( Color fg)
setFocusCycleRoot ( boolean b)
setHorizontalTextPosition ( int position)
SwingConstants. LEFT
SwingConstants. RIGHT
SwingConstants. CENTER
setVerticalTextPosition ( int position)
SwingConstans. TOP
SwingConstans. BOTTOM
SwingConstans. CENTER
setIcon ( Icon c)
JButton
Events:
actionPerformed
mousePressed
jButton1. addActionListener (new java.awt.event. ActionListener () {
public void actionPerformed (java.awt.event.ActionEvent evt) {
jButton1ActionPerformed (evt);
}
});
private void jButton1ActionPerformed (java.awt.event.ActionEvent evt) {
// TODO add your handling code here :
}
Thêm một sự kiện cho control – Netbeans
JTextField
JTextField
Methods:
setText ( String text)
getText ( )
setForeground (Color fg)
Events:
caretUpdate
Một số JTextComponent
JCheckBox
Methods:
setSelected ( boolean b)
isSelected ()
setText ( String text)
getText ()
Events:
actionPerformed: Sự kiện khi checkbox được nhấn
JRadioButton
Methods:
setSelected ( boolean b)
isSelected ()
setText ( String text)
getText ()
Events:
actionPerformed: Sự kiện khi radioButton được nhấn
ButtonGroup group = new ButtonGroup ();
group. add (birdButton);
group. add (catButton);
group. add (dogButton);
group. add (rabbitButton);
group. add (pigButton);
Gom các radioButton thành một nhóm
Methods of JComboBox:
setModel (ComboBoxModel model)
getModel ()
setSelectedIndex (int index)
getSelectedItem ()
getSelectedIndex ()
getItemCount ()
JComboBox
Methods of DefaultComboBoxModel
addElement ( Object o)
getElementAt ( int index)
getIndexOf ( Object item)
getSelectedItem ()
removeAllItems ()
removeItemAt ( int index)
setSelectedItem ( int index)
Khởi tạo từ mảng đối tượng
Khởi tạo từ một Vector
Events:
actionPerformed: Sự kiện khi comboBox thay đổi item hiển thị
A ComboBoxModel : đối tượng quản lý dữ liệu của ComboBox
JComboBox – Ví dụ 14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package demoswingcomponents;
import javax.swing.DefaultComboBoxModel;
public class VD14_DemoComboBox extends javax.swing.JFrame {
public VD14_DemoComboBox() {
initComponents();
}
private void initComponents() {
jComboBox1 = new javax.swing. JComboBox ();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(500, 300));
getContentPane().setLayout(new java.awt.FlowLayout());
jComboBox1.setPreferredSize(new java.awt. Dimension (100, 20));
getContentPane().add( jComboBox1 );
String [] items = new String [] { "Item 1" , "Item 2" , "Item 3" };
DefaultComboBoxModel model = new DefaultComboBoxModel (items);
jComboBox1 .setModel(model);
pack();
}
private javax.swing. JComboBox jComboBox1 ;
}
VD14 : Model là một mảng các giá trị chuỗi
JComboBox – Ví dụ 15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package demoswingcomponents;
public class Person {
private int id;
private String name;
public Person(int id, String name){
this.id = id;
this.name = name;
}
public Person () {
this.id = 0;
this.name = "";
}
public String toString () {
return this.id + " - " + name;
}
}
VD14 : Model là một mảng các đối tượng
JComboBox – Ví dụ 15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package demoswingcomponents;
import javax.swing.*;
public class VD15_DemoComboBox extends javax.swing.JFrame {
public VD15_DemoComboBox() {
initComponents();
Person p1 = new Person (1, "A");
Person p2 = new Person (2, "B");
Person p3 = new Person (3, "C");
Person [] items = new Person [] {p1, p2, p3};
DefaultComboBoxModel model = new DefaultComboBoxModel (items);
model. setSelectedItem (p2);
jComboBox1. setModel (model);
}
private void initComponents() {
jComboBox1 = new javax.swing.JComboBox();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.FlowLayout());
getContentPane().add(jComboBox1);
pack();
}
private javax.swing.JComboBox jComboBox1;
}
JList
Methods of DefaultListModel
addElement (Object e)
get (int index)
getSize ()
getElementAt (int index)
remove (int index)
Elements ()
removeAllElements ()
Methods of JList:
setModel ( ListModel model), getModel ()
getMaxSelectionIndex (), getMinSelectionIndex ()
getSelectedIndex (), getSelectedIndices ()
getSelectedValue (), getSelectedValues ()
Events:
valueChanged
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package demoswingcomponents;
import javax.swing.DefaultListModel;
public class VD16_DemoList extends javax.swing.JFrame {
public VD16_DemoList() {
initComponents();
DefaultListModel model = new DefaultListModel(){
String[] items = new String[] {"Item 1", "Item 2", "Item 3"};
@Override
public int getSize() { return items.length; }
@Override
public Object getElementAt(int i) { return items[i]; }
};
jList1. setModel ( model );
}
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.FlowLayout());
jScrollPane1.setViewportView(jList1);
getContentPane().add(jScrollPane1);
pack();
}
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
}
JList – Ví dụ 16
JList – Ví dụ 17
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package demoswingcomponents;
import javax.swing.DefaultListModel;
public class VD17_DemoListObject extends javax.swing.JFrame {
public VD17_DemoListObject() {
initComponents();
Person p1 = new Person(1, "A"); Person p2 = new Person(2, "B");
Person p3 = new Person(3, "C");
DefaultListModel model = new DefaultListModel();
model.addElement(p1); model.addElement(p2); model.addElement(p3);
jList1.setModel(model);
}
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.FlowLayout());
jScrollPane2.setViewportView(jList1);
getContentPane().add(jScrollPane1);
pack();
}
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
}
JPanel
Sử dụng để gom nhóm các control
Methods:
setBorder ( Border border)
add (Component comp)
Events:
mouseClicked
JPanel – Change the border
Methods:
setBorder ( Border border)
Swing Menu
JToolBar
JTable
Hình ảnh:
Mỗi table cũng có đối tượng TableModel để quản lý dữ liệu
Thường sử dụng DefaultTableModel
JTable
Các phương thức của DefaultTableModel
addColumn ( Object obj)
addRow ( Object obj)
getColumnCount ()
getRowCount ()
getValueAt ( int row, int col)
setValueAt ( Object obj, int row, int col)
Các phương thức của JTable:
setModel ( TableModel tm)
getModel ()
getValueAt ( int row, int col)
getRowCount ()
getColumnCount ()
Events:
mouseClicked
JTable - DefaultTableModel
Khởi tạo model:
Đưa một dòng dữ liệu vào model
String[] columns = new String [] { "Mã NV", "Họ tên", "Giới tính", "Địa chỉ" };
DefaultTableModel model = new DefaultTableModel(null , columns);
int manv =
String hoten =
String phai =
String diachi =
Object[] items = new Object[] {manv, hoten, phai, diachi};
model.addRow(items);
JTable
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.FlowLayout());
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"},
{"10", "11", "12"}
},
new String [] {
"Title 1", "Title 2", "Title 3"
}
));
jScrollPane1.setViewportView(jTable1);
getContentPane().add(jScrollPane1);
pack();
}
JTable – Set column width
1
2
3
4
5
jTable1.setModel(model);
jTable1.getColumnModel().getColumn(0).setPreferredWidth(200);
jTable1.getColumnModel().getColumn(1).setPreferredWidth(400);
jTable1.getColumnModel().getColumn(2).setPreferredWidth(100);
jTable1.getColumnModel().getColumn(3).setPreferredWidth(300);
JOptionPane
1
2
3
4
5
JOptionPane.showMessageDialog(
this,
"Warning !!!",
"Title",
JOptionPane.WARNING_MESSAGE);
public static void showMessageDialog( Component parentComponent, Object message, String title, int messageType)
1
2
3
4
5
JOptionPane.showMessageDialog(
this,
"Message",
"Title",
JOptionPane.INFORMATION_MESSAGE);
Message types:
ERROR_MESSAGE
INFORMATION_MESSAGE
WARNING_MESSAGE
QUESTION_MESSAGE
PLAIN_MESSAGE
JOptionPane
public static int showConfirmDialog( Component parentComponent, Object message, String title, int optionType, int messageType )
1
2
3
4
5
6
7
8
9
1011
12
13
int n = JOptionPane.showConfirmDialog(
this, "Message", "Title", JOptionPane. YES_NO_OPTION , JOptionPane. WARNING_MESSAGE );
if ( n== JOptionPane.YES_OPTION)
{
//YES
}
else
{
//NO
}
Option types:
DEFAULT_OPTION
YES_NO_OPTION
YES_NO_CANCEL_OPTION
OK_CANCEL_OPTION
Message types:
ERROR_MESSAGE
INFORMATION_MESSAGE
WARNING_MESSAGE
QUESTION_MESSAGE
PLAIN_MESSAGE
JOptionPane
1
2
3
4
5
6
7
8
9
1011
12
13
14
15
16
17
18
19
20
Object[] options = new Object[] {"Yes, please !", "Oh, No!"};
int n = JOptionPane.showOptionDialog(
this,
"Message" ,
"Title" ,
JOptionPane. YES_NO_OPTION , //Optiont type
JOptionPane. QUESTION_MESSAGE , //Message type
null, //Không dùng custom icon
options, //Tiêu đề của các button
options[0]); //Button mặc định
if ( n== JOptionPane.YES_OPTION)
{
//YES
}
else
{
//NO
}
Fill the data on the JTable
SWING & JDBC
Fill data on the JTable
1
2
3
4
5
6
7
8
9
1011
12
13
14
15
16
17
18
19
20
package demobasicdbprogramming;
import java.sql.*;
import java.util.Properties;
import javax.swing.table.DefaultTableModel;
public class DB01_ReadNhanVien extends javax.swing.JFrame {
private void LoadData () {
String[] columns = new String [] { "Mã NV" , "Họ tên" ,
"Giới tính" , "Địa chỉ" };
DefaultTableModel model = new DefaultTableModel( null , columns);
try {
//1. Đăng ký driver và tạo kết nối đến CSDL
Driver driver = new org.gjt.mm.mysql.Driver();
DriverManager. registerDriver (driver);
Fill data on the JTable
1
2
3
4
5
6
7
8
9
1011
12
13
14
15
16
17
18
19
20
//2. Tạo kết nối đến CSDL
String conString = "jdbc:mysql://localhost:3306/nhanviendb" ;
Properties info = new Properties();
info.setProperty( "characterEncoding" , "utf8" );
info.setProperty( "user" , "root" );
info.setProperty( "password" , "" );
Connection connection;
connection = DriverManager. getConnection (conString, info);
//3. Tạo đối tượng Statement để thực hiện thao tác dữ liệu mong muốn
Statement statement = connection.createStatement();
String sql = "SELECT * FROM nhanvien" ;
//4. Thực hiện truy xuất (đọc / ghi)
statement.execute(sql);
ResultSet rs = statement.getResultSet();
Fill data on the JTable
1
2
3
4
5
6
7
8
9
1011
12
13
14
15
16
17
18
19
20
21
//5. Xử lý kết quả trả về
while (rs.next()) {
int manv = rs.getInt( "MANV" );
String hoten = rs.getString( "HOTEN" );
String phai = rs.getString( "PHAI" );
String diachi = rs.getString( "DIACHI" );
Object[] items = new Object[] {manv, hoten, phai, diachi};
model.addRow(items);
}
//6. Đóng kết nối
connection.close();
} catch (SQLException ex) {
System. out .println(ex);
}
jTable1 .setModel(model);
}
Fill data on the JTable
1
2
3
4
5
6
7
8
9
1011
12
13
14
15
16
17
18
19
20
21
22
public DB01_ReadNhanVien () {
initComponents ();
LoadData ();
}
private void initComponents () {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation (WindowConstants. EXIT_ON_CLOSE );
jTable1 .setBorder(javax.swing.BorderFactory. createLineBorder ( new java.awt.Color(0, 0, 204)));
jTable1 .setGridColor( new java.awt.Color(0, 0, 0));
jScrollPane1 .setViewportView( jTable1 );
getContentPane (). add ( jScrollPane1 , BorderLayout. CENTER );
pack ();
}
private javax.swing.JScrollPane jScrollPane1 ;
private javax.swing.JTable jTable1 ;
}
Fill data on the JTable
Xem danh sách nhân viên:
Fill data on the JTable
Tìm nhân viên:
Java Look & Feel
SWING JAVA LOOK AND FEEL & CUSTOM EVENT
Java Custom Event
Metal Look & Feel
Windows Look & Feel
Synthetica Look & Feel
Java Look & Feel
Metal Look and Feel
Windows Look and Feel
3D Look and Feel
FH Look and Feel
GTK/Swing Look And Feel
Metouia look and Feel
Napkin Look and Feel
Motif Look and Feel
Java Look & Feel
SmoothMetal
Squareness Look And Feel
TinyLaF
InfoNode Look and Feel
Synthetica Look and Feel
Oyoaha lookandfeel
Skin Look And Feel
Java Look & Feel
UIManager
SwingUtilities.updateComponentTreeUI(JComponent com)
UIManager
UIManager.setLookAndFeel(LookAndFeel laf)
UIManager.setLookAndFeel(String name)
UIManager.setInstalledLookAndFeels(LookAndFeelInfo infos)
UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.getInstalledLookAndFeels();
UIManager.getLookAndFeel();
UIManager.getSystemLookAndFeelClassName();
File đính kèm:
bai_giang_lap_trinh_java_chuong_4_lap_trinh_giao_dien_voi_ja.pptx

