chủ đề 2: thiết kế giao diện - hienlth.info · cd1-cnpm - java hienlth giới thiệu...

140
CD1-CNPM - JAVA HIENLTH Chủ đề 2: Thiết kế Giao diện

Upload: doantram

Post on 15-Jul-2019

218 views

Category:

Documents


0 download

TRANSCRIPT

CD1-CNPM - JAVA HIENLTH

Chủ đề 2: Thiết kế Giao diện

CD1-CNPM - JAVA HIENLTH

Nội dung

•Cấu trúc chung của giao diện

•Giới thiệu AWT

•Giới thiệu Swing

•Trình quản lý giao diện – Layout

•Các thành phần giao diện cơ bản

CD1-CNPM - JAVA HIENLTH

Xây dựng ứng dụng GUI

•Dùng các thư viện hỗ trợ như

• awt (java.awt.*)

• swing (javax.swing.*)

CD1-CNPM - JAVA HIENLTH

Giới thiệu awt

• AWT (Abstract Window Toolkit) được thiết kế phục vụ cho việc tạo ra giao diện người dùng và xử lý đồ họa.

• Các lớp chứa các thành phần để tạo GUI.

• Các lớp quản lý bố cục

• Các lớp xử lý đồ họa và hình ảnh.

• Các lớp xử lý sự kiện

• …

• Là thư viện các lớp hỗ trợ mọi thứ cần thiết cho developer tạo giao diện đồ họa cho các ứng dụng java.

CD1-CNPM - JAVA HIENLTH

Gói AWT của Java

AWTEvent

Font

FontMetrics

Component

Graphics

Object Color

Canvas

Button

TextComponent

Label

List

CheckBoxGroup

CheckBox

Choice

Container Panel Applet

Frame

Dialog FileDialog

Window

TextField

TextArea

MenuComponent MenuItem

MenuBar

Menu

Scrollbar

LayoutManager

CD1-CNPM - JAVA HIENLTH

Giới thiệu awt

•Hầu như tất cả các component trong awt đều kế

thừa từ lớp java.awt.Component.

•Một số component trong awt:

• Label

• Button

• Canvas

• CheckBox

• Container

• List

• Scrollbar

• …

CD1-CNPM - JAVA HIENLTH

Các bước xây dựng ứng dụng GUI

1. Lựa chọn một container: Frame, Window,

Dialog, Applet,…

2. Tạo các control: (buttons, text areas, list,

choice, checkbox,...)

3. Đưa các control vào vùng chứa

4. Sắp xếp các control trong vùng chứa

(Layout).

5. Thêm các xử lý sự kiện (Listeners)

CD1-CNPM - JAVA HIENLTH

Giới thiệu Swing

•Swing là một tập hợp các thành phần giao diện

bao gồm các thành phần đơn giản nhất như

các label, button tới các thành phần phức tạp

như table, tree.

•Hầu hết các thành phần giao diện trong swing

đều kế thừa từ JComponent.

•Bản thân JComponent lại kế thừa từ

java.awt.Container.

CD1-CNPM - JAVA HIENLTH

Các thành phần của Swing

• MVC

• JFrame

• JDestopPane

• JInternalFrame

• JLabel

• JButton

• JTextField

• JCheckBox

• JRadioButton

• JPanel

• JComboBox, JList

• JTable

• JMenu

• JToolBar

• JOptionPane

• JFileChooser

9

CD1-CNPM - JAVA HIENLTH

MVC

Model

View Controller

CD1-CNPM - JAVA HIENLTH

JFrame

CD1-CNPM - JAVA HIENLTH

Swing Components

•Các thành phần của Swing bắt nguồn từ AWT.

•Được viết hoàn toàn bằng JAVA

•Chứa đựng cảm quan (Look and Feel): sự thể

hiện và cách người dùng tương tác với chương

trình.

•Cách dùng: import javax.swing.*

CD1-CNPM - JAVA HIENLTH

GUI Class Hierarchy

Dimension

Font

FontMetrics

Component

Graphics

Object Color

Container

Panel Applet

Frame

Dialog

Window

JComponent

JApplet

JFrame

JDialog

Swing Components

in the javax.swing package

Lightweight

Heavyweight

Classes in the java.awt

package

1

LayoutManager

*

CD1-CNPM - JAVA HIENLTH

Container Classes

Dimension

Font

FontMetrics

Component

Graphics

Object Color

Container

Panel Applet

Frame

Dialog

Window

JComponent

JApplet

JFrame

JDialog

Swing Components

in the javax.swing package

Lightweight

Heavyweight

Classes in the java.awt

package

1

LayoutManager

*

JPanel

CD1-CNPM - JAVA HIENLTH

GUI Helper Classes

Dimension

Font

FontMetrics

Component

Graphics

Object Color

Container

Panel Applet

Frame

Dialog

Window

JComponent

JApplet

JFrame

JDialog

Swing Components

in the javax.swing package

Lightweight

Heavyweight

Classes in the java.awt

package

1

LayoutManager

*

JPanel

CD1-CNPM - JAVA HIENLTH

Swing Components

JMenuItem

JCheckBoxMenuItem

AbstractButton

JComponent

JMenu

JRadioButtonMenuItem

JToggleButton JCheckBox

JRadioButton

JComboBox

JInternalFrame

JLayeredPane

JList

JMenuBar

JOptionPane

JPopupMenu

JProgressBar

JFileChooser

JScrollBar

JScrollPane JSeparator JSplitPane

JSlider

JTabbedPane

JTable JTableHeader

JTextField JTextComponent

JTextArea

JToolBar JToolTip

JTree

JRootPane

JPanel

JPasswordField

JColorChooser

JLabel

JEditorPane

JSpinner

JButton

CD1-CNPM - JAVA HIENLTH

Core Swing Components

JMenuItem

JCheckBoxMenuItem

AbstractButton

JComponent

JMenu

JRadioButtonMenuItem

JToggleButton JCheckBox

JRadioButton

JComboBox

JInternalFrame

JLayeredPane

JList

JMenuBar

JOptionPane

JPopupMenu

JProgressBar

JFileChooser

JScrollBar

JScrollPane JSeparator JSplitPane

JSlider

JTabbedPane

JTable JTableHeader

JTextField JTextComponent

JTextArea

JToolBar JToolTip

JTree

JRootPane

JPanel

JPasswordField

JColorChooser

JLabel

JEditorPane

JSpinner

JButton

CD1-CNPM - JAVA HIENLTH

Swing Components

•Có các thành phần tương ứng với AWT. Tên của các thành phần của Swing thường bắt đầu bằng “J”. VD: JFrame, JLabel, JButton…

•Swing có các thành phần phức tạp hơn mà AWT không có như: tabbed panes, scroll panes, trees, tables…

•Các thành phần của swing có thể hỗ trợ nhiều tính năng hơn so với AWT.

•Để sử dụng các thành phần của Swing cần có chỉ thị: import javax.swing.*

CD1-CNPM - JAVA HIENLTH

Swing Components

•Tất cả các ứng dụng của Swing phải có ít nhất

một top-level container như:

• Frame

• Dialog

• Applet

•Mỗi top-level

container đều

có một content

pane – chứa

tất cả các thành phần visible còn lại, ngoại trừ

menu bar.

Menu Bar

Hello Swing

GO!

Top-level

container

Content

pane

components

CD1-CNPM - JAVA HIENLTH

JFrame

• Mở rộng từ lớp java.awt.Frame

• Mỗi đối tượng JFrame đều có một root pane. Để thamchiếu đến root pane, dùng hàm getContenPane().

• Trước Java 1.5, một thành phần mới cần được thêmvào Content Pane thay vì thêm trực tiếp vào JFrame

frame.getContentPane().add(new JButton(“OK”));

• Từ Java 1.5 trở đi, có thể thêm thành phần mới trựctiếp vào Frame, khi đó nó sẽ tự động thêm vào Content Pane

frame.add(new JButton(“OK”));

CD1-CNPM - JAVA HIENLTH

JFrame

javax.swing.JFrame

+JFrame()

+JFrame(title: String)

+getSize(width: int, height: int): void

+setLocation(x: int, y: int): void

+setVisible(visible: boolean): void

+setDefaultCloseOperation(mode: int): void

+setLocationRelativeTo (c: Component):

void

Creates a default frame with no title.

Creates a frame with the specified title.

Specifies the size of the frame.

Specifies the upper-left corner location of the frame.

Sets true to display the frame.

Specifies the operation when the frame is closed.

Sets the location of the frame relative to the specified component.

If the component is null, the frame is centered on the screen.

CD1-CNPM - JAVA HIENLTH

JFrame

•Methods:

• setTitle (String title)

• setAlwaysOnTop (boolean alwaysOnTop)

• show(), setVisible (boolean b), dispose()

• setResizable (boolean resizable)

•Events:

• mouseClicked, mouseEntered, mousePress,….

• windowClosed, windowOpened, windowIconified,…

• keyPressed, keyTyped, ….

CD1-CNPM - JAVA HIENLTH

JDestopPane

•Methods:

• add (Component component)

• getAllFrames()

• getSelectedFramed()

• findComponentAt (Point p)

• setBackground (Color c)

•Events:

• componentAdded

• componentRemoved

CD1-CNPM - JAVA HIENLTH

JInternalFrame

JDesktopPane MDI

CD1-CNPM - JAVA HIENLTH

JInternalFrame

•Methods:

• setTitle (String title)

• show(), setVisible (boolean b), dispose()

• setClosable (boolean b)

• setResizable (boolean resizable)

•Events:

• mouseClicked, mouseEntered, mousePress,….

• windowClosed, windowOpened, windowIconified,…

• keyPressed, keyTyped, ….

CD1-CNPM - JAVA HIENLTH

Swing Layout Manager

CD1-CNPM - JAVA HIENLTH

Layout Manager

CD1-CNPM - JAVA HIENLTH

Giới thiệu

•Layout là cách thức sắp xếp các component trên một

container, làm cho các component xuất hiện với vị trí

như mong muốn.

•Khi kích thước của container thay đổi, thì kích thước

và vị trí tương đối của các component trong

container cũng thay đổi theo.

CD1-CNPM - JAVA HIENLTH

Các layout manager

• BorderLayout

• BoxLayout

• CardLayout

• FlowLayout

• GridLayout

• GridBagLayout

• SpringLayout

• GroupLayout

• Null Layout

CD1-CNPM - JAVA HIENLTH

Layout Manager

•Ngoài các lớp có sẵn trong gói java.AWT, gói

javax.swing còn cung cấp thêm một số lớp để định

nghĩa layout như:

• BoxLayout

• SwingLayout

• …

•Custom Layout: Xây dựng các lớp thực thi các giao

diện LayoutManger, hoặc LayoutManager2 để định

nghĩa cách sắp xếp các thành phần theo mong muốn.

CD1-CNPM - JAVA HIENLTH

Layout Manager

Left to right,

Top to bottom

c

n

s

ew

FlowLayout GridLayout

BorderLayout

none,

programmer

sets x,y,w,h

null

One at a time

CardLayout GridBagLayout

JButton

CD1-CNPM - JAVA HIENLTH

FlowLayout

•Flow layout sẽ đặt các component theo thứ tự

• Từ trái sang phải

• Khi hết chổ thì đưa các component vào phía bên dưới

và lại bắt đầu từ trái sang phải.

•Kích thước của các component khi đặt vào

container được xác định bằng preferred size.

CD1-CNPM - JAVA HIENLTH

BorderLayout

•BorderLayout là layout manager default của

các đối tượng JPanel.

•Border layout sẽ đặt các component vào trong

các vùng sau của container : top, bottom, left,

right, center.

CD1-CNPM - JAVA HIENLTH

CardLayout

•CardLayout là một dạng bố cục cho phép ta có

thể đặt nhiều component khác nhau trên cùng

một vùng không gian tại các thời điểm khác

nhau.

CD1-CNPM - JAVA HIENLTH

CardLayout

•Các hàm cung cấp bởi CardLayout

• void first(Container);

• void next(Container);

• void previous(Container);

• void last(Container);

• void show(Container, String);

CD1-CNPM - JAVA HIENLTH

GridLayout

•GridLayout trình bày các component lên

container dưới dạng lưới

•Container sẽ được chia thành lưới các ô dưới

dạng nhiều dòng nhiều cột.

• Các ô có kích thước bằng nhau

• Mỗi component sẽ được hiển thị trên 1 ô trong lưới

CD1-CNPM - JAVA HIENLTH

GridLayout

•Cách khởi tạo GridLayout

• public GridLayout(int rows, int columns)

• public GridLayout(int rows, int columns,

int horizontalGap, int verticalGap)

CD1-CNPM - JAVA HIENLTH

GridBagLayout

•GridBagLayout đặt các component trong một lưới các dòng và cột,

• cho phép các component được đặt trên nhiều ô thuộc nhiều dòng và cột.

• các dòng và các cột trong lưới các ô có thể có kích thước khác nhau

•Khi thay đổi kích thước của container, GridBagLayout sẽ thay đổi kích thước của từng ô và thay đổi cách thức đặt các component trên container.

CD1-CNPM - JAVA HIENLTH

GridBagLayout

•Chương trình phải xác định kích thước và các

đặc tính của component bằng cách đưa ra các

ràng buộc cho mỗi component. Các ràng buộc

này sẽ có ảnh hưởng đến cách thức hiển thị

của component trong container.

•Để xác định các ràng buộc, ta phải tạo ra đối

tượng GridBagConstraints

CD1-CNPM - JAVA HIENLTH

GridBagLayout

•Các thuộc tính của GridBagConstraints

• gridx, gridy

• gridwidth, gridheight

• fill

• ipadx, ipady

• insets

• anchor

• weightx, weighty

CD1-CNPM - JAVA HIENLTH

BoxLayout

•Khi đặt các component vào container, BoxLayout dựa vào các thông tin minimum size, prefer size và maximum size.

•Khi BoxLayout đặt các component từ trên xuống dưới, nó sẽ cố đặt các component với kích thước chiều cao xác định trong preferred size.

•Vùng không gian trống sẽ đặt ở phía bên dưới của container

CD1-CNPM - JAVA HIENLTH

BoxLayout

•X Alignment.

• Giá trị của các X Alignment này sẽ từ 0.0 tới 1.0.

• 0.0 ứng với Component.LEFT_ALIGNMENT

• 0.5 ứng với Component.CENTER_ALIGNMENT

• 1.0 ứng với Component.RIGHT_ALIGNMENT.

CD1-CNPM - JAVA HIENLTH

BoxLayout

•Các Invisible Component

• Rigid area

• HorizontalGlue

• VerticalGlue

• Filler

CD1-CNPM - JAVA HIENLTH

SpringLayout

•SpringLayout hoạt động dựa trên việc định nghĩa

mối liên hệ giữa cạnh của các component. Ví dụ,

ta có thể định nghĩa cạnh bên trái của một

component cách đúng 5 pixel so với cạnh phải

của một component khác.

•SpringLayout sẽ tạo kích thước của các

component (chiều cao và chiều rộng) trong

khoảng minimum size và maximum size

•Ràng buộc Spring áp đặt cho một component

thông qua đối tượng SpringLayout.Constraints

CD1-CNPM - JAVA HIENLTH

GroupLayout

•Là một Layout Manager phát triển cho các GUI

builder.

•GroupLayout làm việc với hai chiều : horizontal

và vertical riêng lẻ.

•Được đưa vào kể từ Java SE 6.

CD1-CNPM - JAVA HIENLTH

GroupLayout

•Tổ chức của GroupLayout

• Sequential : các component được sắp xếp tuần tự

theo 1 chiều

• Parallel : Các component được sắp xếp trên cùng 1

vùng không gian (của chiều đang làm việc)

• Vertical : baseline, top, bottom

• Horizontal : left, right, center

CD1-CNPM - JAVA HIENLTH

GroupLayout

•Một group có thể nằm bên trong một group

khác.

•Gap : vùng không gian không nhìn thấy giữa

các component.

•Dùng phương thức addComponent để đưa các

component vào container.

CD1-CNPM - JAVA HIENLTH

LayoutManager - VD

CD1-CNPM - JAVA HIENLTH

JPanel

JPanel

CD1-CNPM - JAVA HIENLTH

JPanel•Giúp tổ chức các thành phần

•Lớp JPanel là lớp con của Jcomponent, Container và Component.

•Có thể có nhiều thành phần (và các khung chứa panel khác) được thêm vào chúng.

•Layout mặc định là FlowLayout

•Constructors• JPanel ();

• JPanel (LayoutManager lm);

•Methods: có các phương thức của các lớp JComponent, Container, Component.

CD1-CNPM - JAVA HIENLTH

JPanel

•Methods:

• setBorder (Border border)

• add (Component comp)

•Events:

• mouseClicked

CD1-CNPM - JAVA HIENLTH

JLabel

CD1-CNPM - JAVA HIENLTH

JLabel

• JLabel có thể chứa văn bản hoặc hình ảnh.

•Constructors

• JLabel (Icon img);

• JLabel (String str);

• JLabel (String str, Icon img, int align); //align có thể

nhận các giá trị: SwingConstant.LEFT, RIGHT,

CENTER, LEADING, TRAILING.

•Methods

• Icon getIcon ();

• void setIcon (ImageIcon i);

• String getText ();

• void setText (String str);

•Methods:• setSize (Dimenstion d)

• setForeground (Color fg)

•Events:• mouseClicked

CD1-CNPM - JAVA HIENLTH

Text Components

JTextComponent

JPasswordField JTextField JTextArea JEditorPane JTextPane

CD1-CNPM - JAVA HIENLTH

JTextField

CD1-CNPM - JAVA HIENLTH

JTextField

•Hộp văn bản trong đó người sử dụng có thể nhập 1

dòng dữ liệu từ bàn phím.

•Constructors

• JTextField ()

• JTextField (String str)

• JTextField (int cols) //cols: maximum length of TextField

• JTextField (String str, int cols)

CD1-CNPM - JAVA HIENLTH

JTextField

•Methods:

• setText (String text)

• getText ()

• setForeground (Color fg)

•Events:

• caretUpdate

CD1-CNPM - JAVA HIENLTH

JTextArea

•Cho phép người dùng nhập văn bản nhiều dòng.

•Constructors• JTextArea ();

• JTextArea (String text);

• JTextArea (int rows, int cols);

• JTextArea (String text, int rows, int cols);

•Methods• void setFont (Font f);

• void setLineWrap (boolean flag); //enable word wrap

CD1-CNPM - JAVA HIENLTH

JPasswordField

• Kế thừa từ JTextField

• Che giấu các ký tự mà người sử dụng nhập vào

• Constructors

• JPasswordField ();

• JPasswordField (int cols);

• Methods

• setEchoChar (char c);

CD1-CNPM - JAVA HIENLTH

Buttons

CD1-CNPM - JAVA HIENLTH

JButton

CD1-CNPM - JAVA HIENLTH

JButton

• Nút nhấn - thành phần người sử dụng nhấp để

kích hoạt một hành động cụ thể.

• Được dẫn xuất từ lớp javax.swing.AbstractButton

• Constructors

• JButton ()

• JButton (Icon icon)

• JButton (String text)

• JButton (String text, ImageIcon icon)

CD1-CNPM - JAVA HIENLTH

JButton

•Methods:

• setText (String text)

• getText ()

• setForeground (Color fg)

• setFocusCycleRoot (boolean b)

•Events

• actionPerformed

• mousePressed

CD1-CNPM - JAVA HIENLTH

JCheckBox

CD1-CNPM - JAVA HIENLTH

JCheckBox

•Cho phép chọn 1 hoặc nhiều lựa chọn

•Constructors

• JCheckBox ()

• JCheckBox (String text)

• JCheckBox (ImageIcon icon)

• JCheckBox (String text, boolean selected)

• JCheckBox (Icon icon, boolean selected)

• JCheckBox (String text, ImageIcon icon, boolean

selected)

• JCheckBox (Action a)

CD1-CNPM - JAVA HIENLTH

JCheckBox

•Methods:

• setSelected (boolean b)

• isSelected ()

• setText (String text)

• getText ()

•Events:

• actionPerformed

CD1-CNPM - JAVA HIENLTH

JRadioButton

ButtonGroup group = new ButtonGroup();

group.add (birdButton);

group.add (catButton);

group.add (dogButton);

group.add (rabbitButton);

group.add (pigButton);

CD1-CNPM - JAVA HIENLTH

JRadioButton

•Chỉ được chọn 1 trong số các lựa chọn

•Constructors

• JRadioButton ()

• JRadioButton (String text)

• JRadioButton (Icon icon)

• JRadioButton (String text, boolean selected)

• JRadioButton (Icon icon, boolean selected)

• JRadioButton (String text, Icon icon, boolean

selected)

• JRadioButton (Action a)

CD1-CNPM - JAVA HIENLTH

JRadioButton

•Methods:

• setSelected (boolean b)

• isSelected ()

• setText (String text)

• getText ()

•Events:

• actionPerformed

CD1-CNPM - JAVA HIENLTH

JComboBox

CD1-CNPM - JAVA HIENLTH

JComboBox

•Hộp danh sách chứa các mục từ đó người sử dụng

có thể lựa chọn một mục khi nhấp vào nó hoặc từ

đánh vào một mục mới.

•Constructors

• JComboBox ();

• JComboBox (ComboBoxModel asModel); //create a

//JComboBox that takes its items from an existing

//ComboBoxModel

• JComboBox (Object [] items);

•Methods

• isEditable ();

• isSelected ();

CD1-CNPM - JAVA HIENLTH

JComboBox

•DefaultComboBoxModel

• Methods:

• addElement (Object o)

• getElementAt (int index)

• getIndexOf (Object item)

• getSelectedItem ()

• removeAllItems ()

• removeItemAt (int index)

• setSelectedItem (int index)

CD1-CNPM - JAVA HIENLTH

JComboBox

•Methods:

• setModel (ComboBoxModel model)

• getModel ()

• setSelectedIndex (int index)

• getSelectedItem ()

• getSelectedIndex ()

• getItemCount ()

•Events:

• actionPerformed

CD1-CNPM - JAVA HIENLTH

JList

CD1-CNPM - JAVA HIENLTH

JList

•Danh sách các mục. Người sử dụng có thể chọn một hoặc nhiều mục (Single-selection vs. multiple-selection)

•Constructors• JList ();

• JList (ListModel dataModel);

• JList (Object [] listData);

•Methods• setSelectionModel(ListSelectionModel.SINGLE_SELEC

TION/SINGLE_INTERVAL_SELECTION/MULTIPLE_INTERVAL_SELECTION)//cho phép chọn 1 hoặc nhiều mục

CD1-CNPM - JAVA HIENLTH

JList

•DefaultListModel

• Methods:

• addElement (Object e)

• get (int index)

• getSize ()

• getElementAt (int index)

• remove (int index)

• Elements()

• removeAllElements ()

CD1-CNPM - JAVA HIENLTH

JList

•Methods:

• setModel (ListModel model), getModel ()

• getMaxSelectionIndex (), getMinSelectionIndex ()

• getSelectedIndex (), getSelectedIndices ()

• getSelectedValue (), getSelectedValues ()

•Events:

• valueChanged

CD1-CNPM - JAVA HIENLTH

JSlider

•Cho phép người sử dụng chọn giá trị nguyên

trong một vùng giá trị xác định.

•Một số đặc tính:

• Tick marks (major and minor)

• Snap-to ticks

• Hướng (ngang hoặc đứng)

CD1-CNPM - JAVA HIENLTH

Swing Menu

CD1-CNPM - JAVA HIENLTH

Menu

JTextComponent

JMenuBar JPopupMenu JAbstractButton JSeparator

JMenuItem

JMenuJCheckBoxMenuItem JRadioButtonMenuItem

CD1-CNPM - JAVA HIENLTH

DialogBox

• Một đối tượng DialogBox phụ thuộc vào một Frame.

• Có 2 loại

• Modal Dialog: sử dụng lớp JOptionPane để tạo hộp thoại loại

này.

• Modaless Dialog: sử dụng lớp JDialog để tạo hộp thoại loại này

• Ngoài ra còn có các lớp: JFileChooser, JColorChooser

CD1-CNPM - JAVA HIENLTH

JOptionPane

CD1-CNPM - JAVA HIENLTH

JOptionPane

CD1-CNPM - JAVA HIENLTH

JOptionPane

CD1-CNPM - JAVA HIENLTH

JOptionPane

• Constructors

• JOptionPane()

• JOptionPane(Object Message)

• JOptionPane(Object message, int messageType)

• JOptionPane(Object message, int messageType, int

optionType)

• JOptionPane(Object message, int messageType, int

optionType, Icon, icon);

CD1-CNPM - JAVA HIENLTH

JOptionPane –Hàm hiển thị Dialog

• Hai hàm dùng để hiển thị Dialog

• void showMessageDialog(…)

• void showOptionDialog(…) //can display a customized

//dialog

• Hàm thường sử dụng:

void showMessageDialog (Component

parentComponent, ObjectMessage);

CD1-CNPM - JAVA HIENLTH

JTree

• Một JTree là một cây gồm nhiều node, trong đó có phải 1 node gọi là root node (nốt gốc).

• Constructor:

• JTree()

• Jtree(DefaultMutableTreeNode root)

• Sử dụng lớp DefaultMutableTreeNode để tạo các node.

• Add một node vào node khác:

Parrent_node.add (Jtree(DefaultMutableTreeNode child_node)

• Hai sự kiện gắn với JTree là mở rộng và thu hẹp một node. Để đăng ký các sự kiện này, dùng hàm addTreeExpansionListener()

CD1-CNPM - JAVA HIENLTH

JTree

•Methods

•getUserObject()

•children()

•getChildAt()

•preorderEnumeration()

•breadthFirstEnumeration()

•depthFirstEnumeration();

postorderEnumeration()

•…

CD1-CNPM - JAVA HIENLTH

JTable

CD1-CNPM - JAVA HIENLTH

JTable

• JTable không chứa hoặc lưu trữ dữ liệu, nó chỉ

cung cấp cách hiển thị dữ liệu.

•Constructor

• JTabel (Object [][] cells, String [] colsName);

• JTabel(AbstractableModel model);

CD1-CNPM - JAVA HIENLTH

JTable

•DefaultTableModel

• addColumn (Object obj)

• addRow (Object obj)

• getColumnCount ()

• getRowCount ()

• getValueAt (int row, int col)

• setValueAt (Object obj, int row, int col)

CD1-CNPM - JAVA HIENLTH

JTable

•Methods:

• setModel (TableModel tm)

• getModel ()

• getValueAt (int row, int col)

• getRowCount ()

• getColumnCount ()

•Events:

• mouseClicked

CD1-CNPM - JAVA HIENLTH

JFileChooser

CD1-CNPM - JAVA HIENLTH

JFileChooser

CD1-CNPM - JAVA HIENLTH

JFileChooser

CD1-CNPM - JAVA HIENLTH

JFileChooser

CD1-CNPM - JAVA HIENLTH

Một số thành phần khác

•JTabbedPane, JScrollPane, JSplitPane,

JLayerPane

•ProgressBar

•JSpinner

•…

CD1-CNPM - JAVA HIENLTH

Look and Feel (Cảm quan)

•Look: đại diện cho thành phần UI bên ngoài của

component

•Feel: đại diện cho phần behave (ví dụ như hiệu

ứng khi hover, click…)

CD1-CNPM - JAVA HIENLTH

Look and Feel (Cảm quan)

• Về cơ bản, có 2 loại Look and Feel:• Skinable

• Non-skinable

• JRE cung cấp các LaF sau:• CrossPlatformLookAndFeel: còn được gọi là Java LaF

hay Metal LaF. LaF này tạo ra giao diện giống nhau trên tất cả các nền tảng. Đây sẽ là LaF mặc định nếu bạn không chỉ ra LaF trong code.

• SystemLookAndFeel: LaF của riêng nền tảng mà ứng dụng đang chạy, được xác định lúc runtime.

• Synth: giúp bạn tạo LaF của riêng bạn với 1 file XML.

• Multiplexing: một cách để sử dụng nhiều LaF cùng lúc.

CD1-CNPM - JAVA HIENLTH

Look and Feel (Cảm quan)

•Thay đổi Look and Feel sau startup

UIManager.setLookAndFeel(lnfName);

SwingUtilities.updateComponentTreeUI(frame);

frame.pack();

CD1-CNPM - JAVA HIENLTH

Look and Feel (Cảm quan)

• Sử dụng GTK look and feel

lnfName =“com.sun.java.swing.plaf.gtk.GTKLookAndFeel”

• Sử dụng Windows look and feel

lnfName = “com.sun.java.swing.plaf.windows.WindowsLookAndFeel”

• Sử dụng Motif look and feel

lnfName = “com.sun.java.swing.plaf.motif.MotifLookAndFeel”

• Sử dụng Metal look and feel

lnfName = “javax.swing.plaf.metal.MetalLookAndFeel”

CD1-CNPM - JAVA HIENLTH

Event Handling

•Các thành phần của swing có thể phát sinh các

sinh các sự kiện được định nghĩa trong

java.awt.event và javax.swing.event.

•Hàm đăng ký sự kiện: addABCListener()

•Hàm hủy đăng ký sự kiện:

removeABCListener()

CD1-CNPM - JAVA HIENLTH

javax.swing.event

CD1-CNPM - JAVA HIENLTH

Selected User Actions

Source Event Type

User Action Object Generated

Click a button JButton ActionEvent

Click a check box JCheckBox ItemEvent, ActionEvent

Click a radio button JRadioButton ItemEvent, ActionEvent

Press return on a text field JTextField ActionEvent

Select a new item JComboBox ItemEvent, ActionEvent

Select an item from a List Jlist ListSelectionEvent

Window opened, closed, etc. Window WindowEvent

Mouse pressed, released, etc. Any Component MouseEvent

Key released, pressed, etc. Any Component KeyEvent

CD1-CNPM - JAVA HIENLTH

Java AWT Event Listener Interfaces

ActionListener

AdjustmentListener

ComponentListener

ContainerListener

FocusListener

ItemListener

KeyListener

MouseListener

MouseMotionListener

TextListener

WindowListener

ListSelectionListener

All are in the java.awt.event or javax.swing.event package

All are derived from EventListener in the java.util package

NOTE: any object that will respond to an event must implement a

listener interface.

CD1-CNPM - JAVA HIENLTH

Selected Event Handlers

Event Class Listener Interface Listener Methods

(Handlers)

ActionEvent ActionListener actionPerformed

(ActionEvent)

ItemEvent ItemListener itemStateChanged

(ItemEvent)

ListSelectionEvent ListSelectionListener valueChanged

(ListSelectionEvent)

CD1-CNPM - JAVA HIENLTH

Adapters• Listeners are typically interfaces, therefore requiring all

methods be implemented

• Use an adapter class to provide convenience implementations

of unused methods:

addWindowListener(new WindowAdapter() {

public void windowActivated(WindowEvent event)

{

System.out.println("Window activated");

}

});

CD1-CNPM - JAVA HIENLTH

Mouse Events (i)

java.awt.event.MouseEvent

+getButton(): int

+getClickCount(): int

+getPoint(): java.awt.Point

+getX(): int

+getY(): int

Indicates which mouse button has been clicked.

Returns the number of mouse clicks associated with this event.

Returns a Point object containing the x and y coordinates.

Returns the x-coordinate of the mouse point.

Returns the y-coordinate of the mouse point.

java.awt.event.InputEvent

+getWhen(): long

+isAltDown(): boolean

+isControlDown(): boolean

+isMetaDown(): boolean

+isShiftDown(): boolean

Returns the timestamp when this event occurred.

Returns whether or not the Alt modifier is down on this event.

Returns whether or not the Control modifier is down on this event.

Returns whether or not the Meta modifier is down on this event

Returns whether or not the Shift modifier is down on this event.

CD1-CNPM - JAVA HIENLTH

Mouse Events (ii)

java.awt.event.MouseListener

+mousePressed(e: MouseEvent): void

+mouseReleased(e: MouseEvent): void

+mouseClicked(e: MouseEvent): void

+mouseEntered(e: MouseEvent): void

+mouseExited(e: MouseEvent): void

Invoked when the mouse button has been pressed on the

source component.

Invoked when the mouse button has been released on the

source component.

Invoked when the mouse button has been clicked (pressed and released) on the source component.

Invoked when the mouse enters the source component.

Invoked when the mouse exits the source component.

java.awt.event.MouseMotionListener

+mouseDragged(e: MouseEvent): void

+mouseMoved(e: MouseEvent): void

Invoked when a mouse button is moved with a button pressed.

Invoked when a mouse button is moved without a button

pressed.

CD1-CNPM - JAVA HIENLTH

Keyboard Events• Capture keyboard events via the KeyListener interface:

keyPressed(KeyEvent e)

keyReleased(KeyEvent e)

keyTyped(KeyEvent e)

java.awt.event.KeyEvent

+getKeyChar(): char

+getKeyCode(): int

Returns the character associated with the key in this event.

Returns the integer keyCode associated with the key in this event.

java.awt.event.InputEvent

Home VK_HOMEPage Up VK_PGUPPage Down VK_PGDN

Arrow Keys VK_UPVK_DOWNVK_RIGHTVK_LEFT

CD1-CNPM - JAVA HIENLTH

Timer Events

• Use timers (the java.awt.Timer class) to control

animations, trigger other events, etc.

javax.swing.Timer

+Timer(delay: int, listener:

ActionListener)

+addActionListener(listener:

ActionListener): void

+start(): void

+stop(): void

+setDelay(delay: int): void

Creates a Timer with a specified delay in milliseconds and an

ActionListener.

Adds an ActionListener to the timer.

Starts this timer.

Stops this timer.

Sets a new delay value for this timer.

CD1-CNPM - JAVA HIENLTH

Handling Simple Action Events

Implementing the listener

interface

Registering the frame to

be a listener for action

events generated by the

two buttons

The method for

responding to an Action

event.

CD1-CNPM - JAVA HIENLTH

Handling Simple Action Events –

a closer look at the event-handling method

actionPerformed is a method

required for all ActionListeners

An Event object’s getSource()

method returns a reference to the

Component object that generated the

event.

CD1-CNPM - JAVA HIENLTH

Alternative Approaches to Listening

• Implement the listener with the main application class, and have the one listener assigned to all components generating the events

• Advantage: simplicity for beginner programmers• Disadvantage: event-handler method may require if-statement or

switch with several branches when multiple components generate the event

• Use inner classes to implement the listeners and create a different instance as each component’s listener.

• Named inner class or anonymous inner class (This is the approach used in the textbook most of the time)

• Advantage: no need to test within the listeners for determining which component sent the event. Each component has its own dedicated listener

• Disadvantage: harder to understand for novice programmers

CD1-CNPM - JAVA HIENLTH

Ví dụ

Panel p1r

(GridLayout 3x2) Panel p3

(BoxLayout - Y)

Panel p4

(GridLayout 1x2)

Panel p5

(GridLayout 1x2)

Panel p6

(GridLayout 2x1)

Content Panel

(BorderLayout)

Panel p2

(BorderLayout)

Panel p1

(BoxLayout - X)

CD1-CNPM - JAVA HIENLTH

Tooltip and border

..myPanel.setOpaque(true); myPanel.setToolTipText("I'm a JPanel");myPanel.setBorder(BorderFactory.createLineBorder(Color.white));

frame.setContentPane(myPanel);..

CD1-CNPM - JAVA HIENLTH

Javax.swing.border

CD1-CNPM - JAVA HIENLTH

Javax.swing.border - Example

CD1-CNPM - JAVA HIENLTH

JProgressBar

• Constructors

• JProgressBar()JProgressBar(int min, int max)

• JProgressBar(int orientation)JProgressBar(int orientation, int min, int max)

• Common methods

• void setValue(int) / int getValue()

• double getPercentComplete()

• void setMinimum(int) / int getMinimum()

• void setMaximum(int) / int getMaximum()

• void setString(String) / String getString()

CD1-CNPM - JAVA HIENLTH

JToolBar

• A JToolBar holds a set of buttons - here all icons but could be text.

• If it is added to a container which is BorderLayout, it can be docked on a side, or left floating.

• Constructors

• JToolBar()JToolBar(int)JToolBar(Stringtitle )JToolBar(String title, int orientation)

• Common Methods

• Component add(Component c)

• void addSeparator()

• void setFloatable(boolean) / boolean isFloatable()

CD1-CNPM - JAVA HIENLTH

JToolBar

CD1-CNPM - JAVA HIENLTH

JToolBar

• A JToolBar holds a set of buttons - here all icons but could be text.

• If it is added to a container which is BorderLayout, it can be docked on a side, or left floating.

..

.. frame is BorderLayout

..

JToolBar toolBar = new JToolBar("Test");

JButton butt1 = new JButton(new ImageIcon("icon.gif"));

toolBar.add(butt1);

..

frame.add(toolBar, BorderLayout.PAGE_START);

CD1-CNPM - JAVA HIENLTH

JSplitPane

• Divide two components with a divider

• Constructor:

• JSplitPane()

• JSplitPane(int newOrientation)

• JSplitPane(int newOrientation, Component newLeftCompon

ent, Component newRightComponent)

• Common methods

• setRightComponent() / setLeftComponent()

• getRightComponent() / getLeftComponent()

• setOrientation() / getOrientation()

• remove (Component c) / remover(int index)

• removerAll()

CD1-CNPM - JAVA HIENLTH

JTabbedPane Separate components with file-folder-style tabs

Constructors

JTabbedPane()

JTabbedPane(int tabPlacement)

tabPlacement: JTabbedPane.TOP, JTabbedPane.BOTTOM, JTabbedPane.LEFT,

JTabbedPane.RIGHT

JTabbedPane(int tabPlacement, int tabLayoutPolicy)

Common methods

addTab(String title, Component component)

addTab(String title, Icon icon, Component component)

addTab(String title, Icon icon, Component component,

String tip)

removertab(int index) / remove(Component c) /removerAll()

Component getTabComponent (int index)

insertTab(String title, Icon icon, Component component, String tip, int index)

CD1-CNPM - JAVA HIENLTH

JScrollBar

• A scrollbar has a 'value' which is the setting of the slider.

• The arguments to the JScrollBar constructor are:

• whether it is horizontal or vertical

• the initial value

• the step change

• minimum value

• maximum value

• Methods

• getValue()

• AdjustmentListener

CD1-CNPM - JAVA HIENLTH

ImagesIcon

• Many Swing components, such as labels, buttons,

and tabbed panes, can be decorated with an icon —

a fixed-sized picture

• Swing provides a particularly useful implementation

of the Icon interface: ImageIcon, which paints an icon

from a GIF, JPEG, or PNG image

CD1-CNPM - JAVA HIENLTH

Images

JFrame frame = new JFrame("I am Celsius");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setBounds(20,30,200,200);

frame.getContentPane().setLayout(null);

ImageIcon icon = new ImageIcon(“images/celsius.jpg", "Celsius");

JLabel label = new JLabel(icon);

label.setBounds(20,20,150,150);

frame.getContentPane().add(label);

frame.setVisible(true);

CD1-CNPM - JAVA HIENLTH

Loading Images Using getResource

CD1-CNPM - JAVA HIENLTH

Loading Images Using getResource

CD1-CNPM - JAVA HIENLTH

Loading Images Using getResource

CD1-CNPM - JAVA HIENLTH

Data Exchange - Example

CD1-CNPM - JAVA HIENLTH

Multiple-Document Interfaces

• Multiple-Document Interfaces

• View multiple documents in a single application

• Swing Implementations

• JDesktopPane class

• JInternalFrame class

CD1-CNPM - JAVA HIENLTH

JDesktopPane

• Constructor

• JDesktopPane()

• Common methods

• public JInternalFrame[] getAllFrames()

• public JInternalFrame selectFrame(boolean forward)

• public JInternalFrame getSelectedFrame()

• public void remove(int index)

• public void removeAll()

CD1-CNPM - JAVA HIENLTH

JInternalFrame

• With the JInternalFrame class you can display a JFrame-like window within another window. Usually, you add internal frames to a desktop pane. The desktop pane, in turn, might be used as the content pane of a JFrame.

• Constructor

• JInternalFrame()JInternalFrame(String)JInternalFrame(String, boolean)JInternalFrame(String, boolean, boolean)JInternalFrame(String, boolean, boolean, boolean)JInternalFrame(String, boolean, boolean, boolean, boolean)

• static int showInternalConfirmDialog(Component, Object)

• static String showInternalInputDialog(Component, Object)static Object showInternalMessageDialog(Component, Object)

• static int showInternalOptionDialog(Component, Object, String, int, int, Icon, Object[], Object)

CD1-CNPM - JAVA HIENLTH

Performing Window Operations on the Internal Frame

• void setDefaultCloseOperation(int)int getDefaultCloseOperation()

• void addInternalFrameListener(InternalFrameListener)void removeInternalFrameListener(InternalFrameListener)

• void setClosed(boolean)boolean isClosed()

• void setIcon(boolean)boolean isIcon()

• void setMaximum(boolean)boolean isMaximum()

• void setSelected(boolean)boolean isSelected()

CD1-CNPM - JAVA HIENLTH

JInternalFrame

• Common methods

• static int showInternalConfirmDialog(Component, Object)static String showInternalInputDialog(Component, Object)static Object showInternalMessageDialog(Component, Object)static int showInternalOptionDialog(Component, Object, String, int, int, Icon, Object[], Object)

• void setLocation(Point)void setLocation(int, int)

• void setBounds(Rectangle)void setBounds(int, int, int, int)

• void setSize(Dimension)void setSize(int, int)

• void setVisible(boolean)• void pack()

CD1-CNPM - JAVA HIENLTH

Rules of Using Internal Frames

• You must set the size of the internal frame: setSize, pack, or setBounds.

• You should set the location of the internal frame: setLocation, setBounds

• To add components to an internal frame, you add them to the internal frame's content pane

• Dialogs that are internal frames should be implemented using JOptionPane or JInternalFrame, not JDialog

• You must add an internal frame to a container (usually a JDesktopPane)

• You need to call show or setVisible on internal frames

• Internal frames fire internal frame events, not window events

CD1-CNPM - JAVA HIENLTH

Refferences

• http://docs.oracle.com/javase/tutorial/uiswing/comp

onents/index.html

• http://docs.oracle.com/javase/tutorial/uiswing/examp

les/components/index.html

CD1-CNPM - JAVA HIENLTH

Câu hỏi và thảo luận

CD1-CNPM - JAVA HIENLTH