You are on page 1of 47

SWING

Layout trong SWING

1
Nội dung
 Giới thiệu về Layout
 Các Layout của AWT
 Các Layout của SWING
 Bài tập
 Kết luận

2
Giới thiệu về Layout

 Layout : Cách bố trí các components


lên container.
 Không dễ dàng gì để tự quản lý vị trí
của các components trên GUI.
 LayoutManager là interface mô tả về
các layout.
 Trong gói AWT có hiện thức sẵn một số
layout, các lớp layout này đều
implement LayoutManager interface.
Layouts có sẵn trong AWT

java.awt.FlowLayout (bố trí dạng dòng


chảy)
java.awt.BorderLayout (bố trí về biên
khung)
java.awt.GridLayout (bố trí dạng lưới đều
nhau)
java.awt.GridBagLayout (bố trí dạng lưới
không đều)
java.awt.CardLayout (bố trí dạng lưng quân
bài)

GUI Slide 4/57


FlowLayout

 Bố trí các component theo dạng chảy xuôi


theo thứ tự mà phần tử này được add vào
container.
 Đây là layout mặc định của Panel.
 Nếu có nhiều component trên container 
Các component có thể được đặt trên nhiều
dòng  Vấn đề gióng hàng (Align)
 Giữa các component, chúng hở nhau theo
chiều dọc (vgap) bao nhiêu, theo chiều
ngang (hgap) bao nhiêu?
GUI Slide 5/57
FlowLayout...
Constructors
FlowLayout()
Tạo FlowLayout mặc định: align= center,
vgap=hgap=5 unit.
FlowLayout(int align)
Tạo FlowLayout với align đã biết, vgap=hgap=5
unit (default).
FlowLayout(int align, int hgap, int vgap)
Tạo FlowLayout với 3 tham số
Trị của align: các dữ liệu static của class
FlowLayout
LEFT CENTER RIGHT
LEADING (phía đầu, tương tự LEFT)
TRAILING (phía đuôi, tương tự RIGHT)
BorderLayout

 Bố trí các component theo dạng ra biên của khung tạo


ra 5 vị trí: EAST, WEST, SOUTH,NORTH, CENTER.
 Đây là layout MẶC ĐỊNH của Frame.
 Nếu container chỉ có 1 component và đặt nó ở vị trí
CENTER thì component này phủ kín container.
 Cú pháp thêm 1 component vào container tại 1 vị trí:
Container.add("East", componentName); // hoặc
Container.add(BorderLayout.EAST, componentName);
 Tương tự cho “West”, “South”, “North”, “Center”

GUI Slide 7/57


GridLayout

 Bố trí các component thành 1 lưới rows


dòng, cols cột đều nhau.

Lưới
Lưới 3x2
4x4

Lưới 1x4

Lưới 1x4
GridLayout...

Constructor
GridLayout()  
Tạo grid layout mặc định 1x1
GridLayout(int rows, int cols)
    Tạo grid layout rows x cols
GridLayout(int rows, int cols, int hgap,
int vgap)
          
GridBagLayout
 Layout dạng lưới cho phép 1 component
chiếm 1 số ô kề nhau theo cả 2 chiều.
 Hình Empoyee Info sau là GridBagLayout
6x4, các label bên trái chiếm 1ô, các
textbox chiếm 3 ô ngang. Dòng “Sex” chiếm
4 ô ngang, 2 checkbox chiếm 2 ô ngang.
CardLayout

 Bố trí các component thành từng lớp như


lưng các quân bài (card).
 Thường dùng Panel để chứa các component.
 Tại 1 thời điểm chỉ có 1 panel hiện hành
(quân bài trên cùng).
 Có thể chuyển qua lại giữa các Panel.
CardLayout...
 Cách tạo GUI với card layout

panel 1
với Layout1
+ các
components Main panel Frame
với
CardLayout
Cơ chế điều
panel2
khiển
với Layout2
+ các
components
Một số Layout SWING
 BoxLayout
 Spring Layout
 Null Layout

13
SWING

Lập trình Giao Diện với JFC

14
Nội dung
 Giới thiệu về AWT
 Giới thiệu về SWING
 Các SWING Component
 Các ứng dụng SWING – Bài tập
 Kết luận

15
GUI là gì?...
 GUI= Container + Components
Container

Components

GUI
Gói AWT của Java
 AWT : abstract windowing toolkit - bộ
công cụ chứa các lớp để tạo cửa sổ.
 AWT là 1 phần của JFC- Java Foundation
Classes.
 Sử dụng: import java.awt.*;
 Gồm nhiều phần tử (class) để tạo GUI.
 Có các lớp quản lý việc bố trí các phần tử.
 Có (event-oriented application) mô
hình ứng dụng hướng sự kiện.
 Có các công cụ xử lý đồ họa và hình ảnh.
 Các lớp sử dụng các tác vụ với clipboard
(vùng nhớ đệm) như GUI
cut, paste. Slide 17/57
Demo AWT
1. import java.awt.*;
2. public class DemoAWT extends Frame
3. {
4. public DemoAWT(String title)
5. {
6. super(title);
7. this.setBounds(100,150,200,200);
8. this.setVisible(true);
9. }
10. public static void main (String[] args) {
11. new DemoAWT("First App");
12. }
13. }

18
So sánh AWT và SWING
AWT SWING

• Xây dựng bằng •Xây dựng bằng


native code JAVA API
• Khó phát triển •Dễ phát triển các
thêm các linh linh kiện
kiện(widget) mới •Có thể thay đổi diện
mạo của linh kiện lúc
runtime
•Mô hình MVC
(Model – View –
Controller) 19
Giới thiệu về JFC(Java Foundation
Class)
 JFC bao gồm các bộ phận sau :
 Các thành phần SWING
 Look & Feel Manager
 Java 2D API
 Drag and Drop support

20
Kiến trúc SWING

21
Demo JFrame
1. import javax.swing.*;
2. public class DemoJFrame extends JFrame
3. {
4. public DemoJFrame(String title) {
5. super(title);
6. this.setBounds(100,150,200,200);
7. this.setVisible(true);
8. }
9. public static void main (String[] args) {
10. new DemoJFrame("Demo Swing");
11. }
12. }

22
SWING Component - JFrame
public class JButtonsDemo extends
LayerPane ContentPane
JFrame
{
Container cn ;
JButton button1 = new JButton(“Java”);
public JButtonsDemo(String title)
{
cn = this.getContentPane();
cn.setLayout(new FlowLayout());
cn.add(button1);
//……….
}
} GlassPane

JFrame()
JFrame(String title )

23

SourceCode
JPanel
 Tương tự như Panel của AWT ,
ContentPane của JFrame thực chất là
1 JPanel
 Constructors:
JPanel()
JPanel( LayoutManager layout)
 Thêm component c vào panel p:
p.add(c) ;
24
JButton
 JButton là lớp kế thừa từ JAbstractButton, diện mạo của
JButton bao gồm: 1 nhãn and/or 1 ảnh diễn tả mục đích
của nút này. Chữ trên nút có thể gạch dưới để mô tả phím
nóng của nút (shortcut key, mnemonic key).
 Constructors
JButton ()
JButton (Icon icon)
JButton(String text)
JButton (String text, Icon icon)
JButton (Action a)
 theButton.setMnemonic(‘J’); // Alt + J

25
JLabel
 JLabel cũng tương tự như Label của AWT
nhưng có thêm tính chất cho phép nạp 1 ảnh
vào nhãn này, xử lý HTML
 Constructors:
JLabel(Icon image)
JLabel(Icon image, int horizontalAlignment)
JLabel(String text)
JLabel(String text, Icon icon,
int horizontalAlignment)
JLabel(String text, int horizontalAlignment)

26
JLabel (tt)
 String content = "<HTML><BODY><FONT
color=RED>Image</FONT>";
 content = content + "<FONT color=BLUE>
<I>JLabel
demo</I></FONT></BODY></HTML>";
 JLabel lbl = new JLabel(content , Img ,
SwingConstants.LEFT);

27
JTextField
 Constructors
JTextField()
JTextField(Document doc,
String text, int columns)
JTextField(int columns)
JTextField(String text)
JTextField(String text,
int columns)
28
JTextArea
Constructors:
 JTextArea()          
 JTextArea(Document doc)
JTextArea(Document doc,
String txt,int rows,int cols)
 JTextArea(int rows,int cols)
 JTextArea(String text)
JTextArea(String text, int rows,
int cols)
29
Nhập bằng lựa chọn với JCheckBox,
JRadioButton, JList
 JCheckbox : Cho phép chọn nhiều lựa chọn
 JRadioButton : Chọn 1 trong nhóm lựa chọn
(lớp ButtonGroup)
 JList : Danh sách chuỗi lựa chọn
 JComboBox
combobox =1 text field + 1 drop down list

30
Demo JRadioButton - JCheckBox
ButtonGroup Grp = new ButtonGroup();
JRadioButton rad1 = new JRadioButton("Male",true);
JRadioButton rad2 = new JRadioButton("Female",false);
Grp.add(rad1); Grp.add(rad2);

Source Code

31
JList
 Constructor
JList()
JList(Object [] A)
JList(ListModel A)
JList(Vector A)

Source Code

32
JComboBox
 Constructor
 JComboBox();
 JComboBox(ComboBoxModel model);
 JComboBox(Object[] arr);
 JComboBox(Vector aVec);

Source Code

33
JMenu

34
JMenu JMenuBar

File

New
JMenuItem
Open
JMenuBar mBar = new JMenuBar
JMenu mFile = new JMenu(“File”);
mBar.add(mFile); this.setJMenuBar(mBar);

JMenuItem()    
JMenuItem(Action a)
JMenuItem(Icon icon)
JMenuItem(String text)
JMenuItem(String text, Icon icon)
JMenuItem(String text,int mnemonic) 35
Demo Menu
Source Code
public void mousePressed(MouseEvent m)
{
if ( m.getModifiers() == InputEvent.BUTTON3_MASK )
app.demoPopup.show(app , m.getX() , m.getY());
}

36
Menu Demo

Source Demo Menu1.java

37
SWING

Dialog

38
Nội dung
 Giới thiệu class JOptionPane
 Hiển thị hình ảnh trong SWING
 Bài tập
 Kết luận

39
JOptionPane

 Hiển thị một Message với chỉ một


button “OK”
 Hiển thị Message với 2 hay 3 Button.
1.)    "Yes" and "No"
2.)    "Yes", "No" and "Cancel"
3.)    "Ok", and "Cancel"
 Hiển thị một hộp thoại nhập với 2
button “OK” và “Cancel”
Các phương thức của class

 showMessageDialog(): hiển thị Message đơn


giản với một nút “OK”.
 showInputDialog(): hiển thị một hộp thoại
input. Method trả về một String ( vừa nhập ).
 showConfirmDialog(): And the last or third
method is the showConfirmDialog() which asks
the user for confirmation (Yes/No) by displaying
message. This method return a numeric value
either 0 or 1. If you click on the "Yes" button then
the method returns 1 otherwise 0.

GUI Slide 41/57


import javax.swing.*;
import java.awt.event.*;

public class ShowDialogBox{ Demo
  JFrame frame;
  public static void main(String[] args){
    ShowDialogBox db = new ShowDialogBox();
  }

  public ShowDialogBox(){
    frame = new JFrame("Show Message Dialog");
    JButton button = new JButton("Click Me");
    button.addActionListener(new MyAction());
    frame.add(button);
    frame.setSize(400, 400);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  public class MyAction implements ActionListener{
    public void actionPerformed(ActionEvent e){
      JOptionPane.showMessageDialog(frame,"Roseindia.net");
    }
  }
}
Các phương thức khác - Demo
Kết quả …

GUI
ShowInputDialog
Các Dialog chuẩn của Window
 JFileChooser
 JColorChooser

46
JFileChooser
 Cho phép chọn File
 Cho phép Save
 Có thể hiển thị theo mode :
fc.setFileSelectionMode(JFileChooser.DI
RECTORIES_ONLY);
fc.setFileSelectionMode(JFileChooser.FIL
ES_AND_DIRECTORIES);

47

You might also like