Chương 10

Lập Trình Giao Diện

Chương 10: Lập trình giao diện

o Xử lý xử kiện trong Java

o Giới thiệu AWT

o Giới thiệu Swing

o Tạo giao diện với Swing

o Tạo giao diện với AWT

Xử lý sự kiện trong Java

o Quá trình lặp sự kiện (event loop) được tích hợp sẵn

trong thành phần giao diện của Java

o Tương tác với một thành phần giao diện (như nút

lệnh) làm cho một sự kiện (event) xảy ra.

o Một sự kiện (Event) là một đối tượng o Cần tạo các bộ nghe (Listeners) cho các sự kiện

– Listener là một giao diện (interface); Chúng ta tạo ra một Listener bằng cách thực thi (implementing) giao diện đó

o Phương thức Listener lấy sự kiện xảy ra làm tham số

Giới thiệu AWT

o AWT(Abstract Window Toolkit) là tập hợp các lớp java cung cấp hỗ trợ thiết kế, xây dựng một GUI (Graphic User Interface)

o Có mặt trong mọi phiên bản của Java o Tạm đủ cho nhiều ứng dụng o Sử dụng các điều khiển được định nghĩa bởi chính hệ

điều hành của bạn

o Khó để xây dựng các giao diện hấp dẫn o Các gói cần sử dụng:

– java.awt.*; – java.awt.event.*;

Giới thiệu AWT

AWTEvent

Container

Panel

Applet

Font

Button

Window

Frame

FontMetrics

Label

Dialog

FileDialog

TextField

TextComponent

Object

Color

TextArea

Graphics

List

Component

Choice

CheckBox

LayoutManager

CheckBoxGroup

Canvas

MenuComponent

MenuItem

Menu

MenuBar

Scrollbar

Giới thiệu Swing

o Tương tự AWT o Chỉ có từ Java 1.2 o Có thêm nhiều điều khiển, các điều khiển cũng linh

hoạt hơn

o Dễ dàng tạo các giao diện đẹp o Gói cần sử dụng: javax.swing.*;

So sánh AWT và Swing

o Swing phong phú hơn, chậm hơn và phức tạp hơn  Hiện nay đã được cải thiện về tốc độ rất nhiều

o Swing linh động hơn và dễ nhìn hơn o Swing và AWT không tương thích với nhau – chỉ có

thể sử dụng 1 trong 2.

o Swing thêm J vào trước các điều khiển của AWT: o VD: AWT: Button b = new Button ("OK"); Swing: JButton b = new JButton("OK");

Tạo một GUI

1. Tạo các vùng hiển thị: Frame/Dialog hoặc Applet

2. Tạo ra một số thành phần (component) giao diện

3. Thêm các thành phần vào các vùng hiển thị

4. Sử dụng một cách bố trí giao diện (layout) để sắp xếp các thành phần lên cửa sổ

5. Thêm các Listeners, thông thường là mỗi listener được gắn vào một thành phần trên giao diện

6. Thêm các phương thức vào các Listeners để thực hiện công việc cần thực hiện

Các Component của GUI

o Container:  Bộ chứa.  Các Component thường dùng là: TextFields,

Labels, CheckBoxes, TextArea, Button, Choice, List, Scrollbars,…

o Component:

 Các thành phần giao diện.  Các bộ chứa thường sử dụng là Panel (và Applet),

Window, và Frame

o Chức năng của Container là chứa và hiển thị các

Component.

o Một bộ chứa cũng là một thành phần giao diện -> các

bộ chứa có thể được lồng vào nhau.

Các Component thường dùng

TẠO GIAO DIỆN NGƯỜI DÙNG ĐỒ HỌA VỚI Swing

Cách tạo GUI với Swing

1. Tạo cửa sổ, thường là JFrame hoặc JApplet

2. Dùng phương thức setLayout(LayoutManager manager) để chọn một kiểu bố trí giao diện

3. Tạo các thành phần giao diện như button, panel, ….

4. Gắn các thành phần giao diện vào cửa sổ hiển thị

5. Viết các Listener và gắn chúng vào các thành phần giao diện tương ứng.

6. Hiển thị cửa sổ ra màn hình

Các gói cần thiết

javax.swing.*: chứa các thành phần swing

java.awt.*: Chứa các kiểu bố trí giao diện (layout manager)

java.awt.event.*: Chứa các listener

Tạo một Container

Cách 1: Khai báo kế thừa containter ở khai báo lớp: • class CuaSo extends JFrame; • class CuaSo extends JApplet;

Cách 2: Dùng hàm tạo của container tương ứng • JFrame myFrame = new JFrame(); • JFrame myFrame = new JFrame(“Tieu de”); • JApplet myApplet = new JApplet();

Chọn một kiểu bố trí giao diện

o Dùng phương thức: setLayout(new XLayout ()); o Các layout thường dùng: BorderLayout, Flow Layout,

Grid Layout, Gridbag Layout và “NullLayout”

o BorderLayout

 Chia cửa sổ thành 5 vùng  Là kiểu layout mặc định

o FlowLayout

 Các thành phần được thêm vào từ trái qua phải, từ

trên xuống GridLayout

 Các thành phần được đặt trong lưới hình chữ nhật  Mỗi mắc lưới đều có kích thước và hình dáng giống

nhau o “NullLayout”:

o Lập trình viên tự xác định vị trí đặt component.

BorderLayout

public class BorderLayoutExample extends JApplet { public void init () { setLayout(new BorderLayout ()); add(new JButton("One"),BorderLayout.NORTH); add(new JButton("Two"),BorderLayout.WEST); add(new JButton("Three"),BorderLayout.CENTER); add(new JButton("Four"),BorderLayout.EAST); add(new JButton("Five"),BorderLayout.SOUTH); add(new JButton("Six")); } }

FlowLayout

public class FlowLayoutExample extends JApplet { public void init () { setLayout(new FlowLayout ()); add(new JButton("One")); add(new JButton("Two")); add(new JButton("Three")); add(new JButton("Four")); add(new JButton("Five")); add(new JButton("Six")); } }

Lồng các thành phần giao diện

Trong Swing, JPanel vừa là một Container vừa là một Component. Nó có thể chứa các component khác và nó cũng có thể được đặt vào các container khác.

Thông thường trong một cửa sổ, người ta sẽ tạo ra nhiều JPanel, sắp xếp chúng trên cửa sổ và đặt các thành phần giao diện vào các JPanel này

FlowLayout

public class GridLayoutExample extends JApplet { public void init() { setLayout(new GridLayout(2, 4)); add(new JButton("One")); add(new JButton("Two")); add(new JButton("Three")); add(new JButton("Four")); add(new JButton("Five")); } }

Null Layout

o Người lập trình phải tự định nghĩa o Để thiết lập cách trình bày là Null Layout cho một container ta chỉ việc gọi phương thức setLayout(null) với tham số là null.

o Một số phương thức của lớp trừu tượng Component dùng để định vị và qui định kích thước của component khi đưa chúng vào khung chứa trình bày theo kiểu kiểu tự do:

- public void setLocation(Point p) - public void setSize(Dimension p) - public void setBounds(Rectangle r)

- MyButton.setSize(new Dimension(20, 10)); - MyButton.setLocation(new Point(10, 10)); - MyButton.setBounds(10, 10, 20, 10);

o Ví dụ:

Frame fr = new Frame("NullLayout Demo"); fr.setLayout(null); Button buttOk = new Button("OK"); buttOk.setBounds(100, 150, 50, 30); Button buttCancel = new Button("Cancel"); buttCancel.setBounds(200, 150, 50, 30);

import java.awt.*; class NullLayoutDemo{ public static void main(String args[]){ Checkbox checkBut = new Checkbox("Check box", true);

checkBut.setBounds(100, 50, 100, 20); List li = new List(); for (int i=0; i<5; i++){ }

li.add(Integer.toString(i));

21

li.setBounds(200, 50, 50, 50); fr.add(buttOk); fr.add(buttCancel); fr.add(checkBut); fr.add(li); fr.setBounds(10, 10, 400, 200); fr.setVisible(true);

} }

22

Ví dụ

Container container = new JFrame() or JApplet(); JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout()); p1.add(new JButton("A"), BorderLayout.NORTH); // also add buttons B, C, D, E JPanel p2 = new JPanel(); p2.setLayout(new GridLayout(3, 2)); p2.add(new JButton("F")); // also add buttons G, H, I, J, K JPanel p3 = new JPanel(); p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS)); p3.add(new JButton("L")); // also add buttons M, N, O, P container.setLayout(new BorderLayout()); container.add(p1, BorderLayout.CENTER); container.add(p2, BorderLayout.SOUTH); container.add(p3, BorderLayout.EAST);

Tạo các component

o Dùng các hàm tạo tương ứng để tạo đối tượng o Ví dụ:

 JButton okButton = new JButton(“OK”);  JCheckBox namCheckBox=new JCheckBox(“Nam”);

o JLabel – Nhãn: dùng để hiển thị các chuỗi ký tự o JTextField – textbox 1 dòng o JTextArea – textbox nhiều dòng o JButton – nút lệnh. o JPanel – Khung: dùng để chứa các component khác o JCheckBox – checkbox o JComboBox – danh sách thả

Tạo JLabel

o Dùng để tạo các nhãn o Các hàm dựng (phương thức khởi tạo):

JLabel label = new JLabel(); JLabel label = new JLabel("This is a JLabel");

 JLabel()  JLabel(String labeltext)  JLabel(String labeltext, int alignment)

o Các phương thức:  setFont(Font f)  setText(String s)  getText( )

JTextField

o Textbox 1 dòng cho phép hiển thị text hoặc nhận dữ liệu

do người dùng nhập vào.

o Các hàm dựng:  JTextField()  JTextField(int columns)  JTextField(String s)  JTextField(String s, int columns)

o Các phương thức:

 setEchoChar(char)  setText(String s)  getText( )  setEditable(boolean)  isEditable()

JTextArea

o Là một textbox có nhiều dòng o Tạo một JTextArea

 Tạo một phần tử (element)  Chỉ ra số dòng hay số cột (tùy chọn)  Chỉ ra vị trí của điều khiển trên màn hình

o Các hàm dựng:  JTextArea( )  JTextArea(int rows, int cols )  JTextArea(String text)  JTextArea(String text, int rows, int cols)

JTextArea

o Các phương thức  setText(String)  getText()  setEditable(boolean)  isEditable()  insertText(String, int)  replaceText(String, int, int)

JButton

JButton b1 = new JButton(); JButton b2 = new JButton("Click me!");

o Các nút nhấn trên giao diện o Các hàm dựng:  JButton()  JButton(String text)

JCheckBoxes/JRadioButtons

o JCheckBoxes (): Người dùng có thể chọn nhiều mục

trong nhóm

o JRadioButtons (): Người dùng chỉ có thể chọn một

mục duy nhất trong nhóm

o Tạo JCheckBox hoặc JRadioButton:

 Tạo một phần tử (element)  Khởi tạo giá trị ban đầu (có giá trị selected hay

unselected)

 Chỉ ra vị trí trên màn hình  Hiển thị ra màn hình

JCheckBoxes/JRadioButtons

o Các hàm dựng để tạo JCheckBox:

 JCheckBox()  JCheckBox(String text)

o Các hàm dựng để tạo JRadioButton:

 JRadioButton()  JRadioButton(String text)

o Sau khi tạo các JRadioButton, ta phải tạo đối tượng ButtonGroup để thêm các JRadioButton vào một nhóm.  buttonGroup.add(radioButton)

JComboBox (hộp thả)

o Tạo ra danh sách có nhiều lựa chọn o Các bước thực hiện:

 Tạo một JComboBox bằng hàm tạo

JComboBox();

 Thêm lần lượt các mục (kiểu String) vào danh

sách bằng phương thức addItem(String).

o Thêm JComboBox vào container o Các phương thức  getItemCount().  getItemAt(int).

Ví dụ:

JButton button = new JButton("Click me!"); JLabel label = new JLabel("This is a JLabel"); JTextField textField1 = new JTextField("This is the initial text"); JTextField textField2 = new JTextField("Initial text", columns); JTextArea textArea1 = new JTextArea("Initial text"); JTextArea textArea2 = new JTextArea(rows, columns); JTextArea textArea3 = new JTextArea("Initial text", rows, columns); JCheckBox checkbox = new JCheckBox("Label for checkbox"); JRadioButton radioButton1 = new JRadioButton("Label for button"); ButtonGroup group = new ButtonGroup(); group.add(radioButton1); group.add(radioButton2); etc.

Gắn các component vào các container

o Đối với FlowLayout, GridLayout, và BoxLayout

 Sử dụng phương thức add: container.add(component);

 Phương thức này sẽ thêm component vào vị trí có

sẵn kế tiếp

o Đối với BorderLayout, sử dụng phương thức add như

sau:

container.add(component, BorderLayout.position);

 position là NORTH, SOUTH, EAST, WEST  Nếu đặt ở giữa (CENTER) thì không cần tham số

thứ 2

Tạo các listener

public void actionPerformed(ActionEvent event) { // Đoạn mã xử lý

o Cách 1: Tạo một lớp riêng cho mỗi listener JButton okButton = new JButton("OK"); okButton.addActionListener(new MyOkListener()); class MyOkListener implements ActionListener { } }

Tạo các listener

o Cách 2: Sử dụng một lớp nội vô danh (anonymous

inner class) JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { // Đoạn mã xử lý } } );

Cách này thường dùng khi đoạn mã xử lý sự kiện ngắn

và chỉ được sử dụng ở một nơi trong chương trình

Cấu trúc một lớp giao diện (không kế thừa)

Định nghĩa các component và gắn vào các listener

Sử dụng một lớp nội suy để xử lý sự kiện

class SomeClass { JFrame frame; JButton button; public static void main(String[] args) { new SomeClass().createGui(); } void createGui() { frame = new JFrame(); button = new JButton("OK"); frame.add(button); // (uses default Layout) button.addActionListener(new MyOkListener()); } class MyOkListener implements ActionListener { public void actionPerformed(ActionEvent event) { // Code to handle button click goes here } }}

Cấu trúc một lớp giao diện (kế thừa)

Định nghĩa các component và gắn vào các listener

Sử dụng một lớp nội suy để xử lý sự kiện

class SomeClass extends JFrame { // JFrame frame; // Don't need this JButton button; public static void main(String[] args) { new SomeClass().createGui(); } void createGui() { // frame = new JFrame(); // Don't need this button = new JButton("OK"); add(button); // Was: frame.add(button); button.addActionListener(new MyOkListener()); } class MyOkListener implements ActionListener { public void actionPerformed(ActionEvent event) { // Code to handle button click goes here }}}

Các component và các listener tương ứng

o JButton, JMenuItem, JComboBox, JTextField:

– addActionListener(ActionListener)

• public void actionPerformed(ActionEvent event)

o JCheckBox, JRadioButton:

– addItemListener(ItemListener)

• public void itemStateChanged(ItemEvent event)

o JTextArea

– getDocument().addDocumentListener(DocumentListener) • public void insertUpdate(DocumentEvent event) • public void removeUpdate(DocumentEvent event) • public void changedUpdate(DocumentEvent event)

Kích hoạt và vô hiệu hóa các thành phần

o anyComponent.setEnabled(enabled);

 Enabled = true: Kích hoạt,  Enabled = false: Vô hiệu hóa

Dialog (hộp thoại)

o Có 2 loại hộp thoại

 Modal: Luôn hiển thị trên các cửa sổ khác  Non-modal

o Java cung cấp nhiều hộp thoại kiểu modal như: o Lập trình viên có thể tự tạo hộp thoại với Jdialog

nhưng chúng mặc nhiên là nonmodal

Message Dialog (Hộp thoại Thông báo)

o JOptionPane.showMessageDialog(parentJFrame, This

is a JOptionPane \"message\“ dialog.")

o showMessageDialog là một phương thức tĩnh của

JOptionPane

o “parentJFrame” thường là cửa sổ giao diện chính (sử

dụng null nếu không có một giao diện chính)

Comfirm Dialog (Hộp thoại xác nhận)

o int yesNo =

JOptionPane.showConfirmDialog(parentJFram e, "Is this what you wanted to see?");

o if (yesNo == JOptionPane.YES_OPTION) { ... }

Input Dialog (Hộp thoại nhập liệu)

• String userName =

JOptionPane.showInputDialog(parentJFrame," What is your name?")

Option Dialog (Hộp thoại tùy chọn)

o Object[] options = new String[] {"English",

"Chinese", "French", "German" };

o int option =

JOptionPane.showOptionDialog(parentJFrame, "Choose an option:", "Option Dialog", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); // use as default

Option Dialog (Hộp thoại tùy chọn)

o Tham số thứ 4 có thể là:

JOptionPane.YES_NO_CANCEL_OPTION o Tham số thứ 5 xác định biểu tượng cho hộp thoại

ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, hoặc PLAIN_MESSAGE o Tham số thứ 6 (null ở trên) có thể xác định một icon

tùy chọn

Load file Dialog (Hộp thoại load file)

• JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Load which file?"); • int result = chooser.showOpenDialog(enclosingJFrame); if (result == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); // use file } • Hộp thoại có thể trả về CANCEL_OPTION hoặc

ERROR_OPTION

• Một đối tượng file sẽ được trả về

Save file Dialog (Hộp thoại save file)

o JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(“Save file as?"); o int result = chooser.showSaveDialog(enclosingJFrame); if (result == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); // use file } o Hộp thoại có thể trả về CANCEL_OPTION hoặc

ERROR_OPTION

o Một đối tượng file sẽ được trả về

Đóng cửa sổ

o gui.setDefaultCloseOperation(JFrame.EXIT_ON_C

LOSE);

o Các tùy chọn khác: DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, và DISPOSE_ON_CLOSE

TẠO GIAO DIỆN NGƯỜI DÙNG ĐỒ HỌA VỚI AWT

Label (nhãn)

o Nhãn được dùng để trình bày một chuỗi văn bản ra

màn hình.

o Một số phương thức của Label: public Label(); // tạo nhãn public Label(String s); // tạo nhãn với nội dung s public Label(String s, int align); // tạo và canh lề void setText(String s); // đặt nội dung nhãn void setAlignment(int align); // canh lề nhãn

Label (nhãn)

Font font = new Font("Courier", Font.BOLD, 20); label = new Label(“Chương trình đầu tiên"); label.setFont(font); add(label);

private Label label; public void init(){ } public void paint(Graphics g){ showStatus("Nội dung của label: “ + label.getText()); }

import java.applet.Applet; import java.awt.*; public class DemoLabel extends Applet{ }

Button (nút nhấn)

o Một số phương thức của Button  Button(); // tạo nút nhấn  Button(String s); // tạo nút nhấn có tên s  void setLabel(String s); // đổi tên nút  String getLabel(); // lấy tên nút nhấn

o Để lắng nghe sự kiện nhấn nút ta cần cài đặt giao tiếp

ActionListener.

Button (nút nhấn)

Text Field (ô văn bản)

o Ô văn bản cho phép nhận dữ liệu từ bàn phím trên

một dòng

o Một số phương thức

 TextField(...); // các cấu tử  void setEditable(boolean b); // đặt/tắt chế độ nhập  void setEchoChar(char c); // đặt kí tự hiển thị

o Đối tượng nghe cần cài đặt 2 giao tiếp

 ActionListener  TextListener

• Cài đặt phương thức textValueChanged();

import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class DemoTextField extends Applet implements

ActionListener{

txtEdit = new TextField("Your name here"); txtPass = newTextField(12); txtPass.setEchoChar('*'); txtPass.addActionListener(this); txtReadOnly = newTextField("This text is read only"); txtReadOnly.setEditable(false);

private TextField txtEdit; private TextField txtReadOnly; private TextField txtPass; private final String PASSWORD = "Java"; public void init(){ // xem tiếp ở slide kế tiếp

56

add(txtEdit); add(txtPass); add(txtReadOnly);

txtReadOnly.setText("Password is valid");

if(txtPass.getText().equals(PASSWORD)) else

txtReadOnly.setText("Invalid password !");

} public void actionPerformed(ActionEvent event){ } }

57

Choice (lựa chọn)

o Choice cung cấp khả năng lựa chọn một trong số các

hạng mục sẵn có. o Một số phương thức  Choice(); // cấu tử  void addItem(String s); // thêm item là s  String getItem(int index);// lấy item có chỉ số index  String getSeclectedItem(); // trả về item được chọn  int getSelectedIndex(); // trả về index của item

được chọn

o Lớp nghe cài đặt giao tiếp ItemListener

 Cài đặt phương thức itemStateChanged(...)

import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class DemoChoice extends Applet implements

ItemListener{

choice = newChoice(); choice.addItem("TimesRoman"); choice.addItem("Courier"); choice.addItem("Helvetica"); choice.addItemListener(this);

private Choice choice; private TextField txtText; private Font font; public void init(){ // xem tiếp ở slide kế tiếp

59

txtText = new TextField("Sample Text", 16); txtText.setEditable(false); font = newFont(choice.getItem(0),Font.PLAIN, 12); txtText.setFont(font); add(choice); add(txtText);

font = newFont(choice.getSelectedItem(), Font.PLAIN, 12); txtText.setFont(font);

} public void itemStateChanged(ItemEvent event){ } }

60

Check Box (Hộp đánh dấu)

o Checkbox cung cấp các hộp tuỳ chọn cho người dùng o Một số phương thức

 Checkbox(...); // các cấu tử  void setLabel(Strings); // đặtnhãn mới  booleangetState(); // lấy trạngtháihiệntại

o Lớp nghe cài đặt giao tiếp ItemListener

 Cài đặt phương thức itemStateChanged(...)

checkBold = new Checkbox("Bold"); checkItalic = new Checkbox("Italic"); checkBold.addItemListener(this); checkItalic.addItemListener(this); txtText = new TextField("Sample Text", 16); Font font = new Font("Courier", Font.PLAIN, 14); txtText.setFont(font);\

import java.applet.Applet; Import java.awt.*; Import java.awt.event.*; public classDemoCheckbox extends Applet implements ItemListener{ private Checkbox checkBold; private Checkbox checkItalic; privateTextFieldtxtText; public void init(){ //xem tiếp ở slide kế tiếp

62

add(txtText); add(checkBold); add(checkItalic);

int valBold = Font.PLAIN; int valItalic = Font.PLAIN; if(checkBold.getState()) valBold = Font.BOLD; if(checkItalic.getState()) valItalic = Font.ITALIC; Font font = new Font("Courier", valBold + valItalic, 14); txtText.setFont(font);

} public void itemStateChanged(ItemEvent event){ } }

63

Check Box Group & Radio Button

o Các Checkboxcó thể được đặt trong một

CheckboxGroup để tạo ra các Radio Button.

CheckboxGroupg = new CheckboxGroup(); Checkbox radio1 = new Checkbox(“Radio1”, g, true); Checkbox radio2 = new Checkbox(“Radio2”, g, false); Checkbox radio3 = new Checkbox(“Radio3”, g, false);

o Vídụ: Tạo 3 radio button thuộc cùng một nhóm. Ban đầu radio1 được chọn. Tại mỗi thời điểm chỉ có thể chọn một trong 3 radio.

group = new CheckboxGroup(); plain = new Checkbox("Plain", group,true); bold = new Checkbox("Bold", group, false); italic = new Checkbox("Italic", group, false); txtText = new TextField("Sample Text"); txtText.setFont(new Font("Courier", Font.PLAIN, 14)); plain.addItemListener(this); bold.addItemListener(this); italic.addItemListener(this);

// Cac import can thiet... public class DemoRadio extends Applet implements ItemListener{ private Checkbox plain, bold, italic; private CheckboxGroup group; private TextFieldtxtText; public void init(){ //xem tiếp ở slide tiếp theo

65

add(txtText); add(plain); add(italic); add(bold);

int mode = 0; if(event.getSource() == plain) mode = Font.PLAIN; if(event.getSource() == italic) mode = Font.ITALIC; if(event.getSource() == bold) mode = Font.BOLD; txtText.setFont(newFont("Courier", mode, 14));

} public void itemStateChanged(ItemEvent event){ } }

66

List (danh sách)

o List cho phép người dùng chọn một hay nhiều item từ

một danh sách các item

o Một số phương thức

 List(); // cấu tử mặc định  List(int items, boolean ms); // cấu tử mở rộng  String getSeclectedItem(); // lấy lại thành phần

được chọn

o Lớp nghe cài đặt giao tiếp ItemListener và/hoặc

ActionListener

// Cac import can thiet... public class DemoList extends Applet implements ItemListener,

ActionListener{

colorList = newList(3, false); colorList.add("White"); colorList.add("Black"); colorList.add("Yellow"); colorList.add("Green"); colorList.addItemListener(this); colorList.addActionListener(this); add(colorList);

private List colorList; public void init(){ } //xem tiếp ở slide tiếp theo

68

List list = (List) event.getSource(); showStatus("Item " + list.getSelectedIndex() + " selected");

List list = (List) event.getSource(); Strings = list.getSelectedItem(); if(s.equals("White")) setBackground(Color.WHITE); if(s.equals("Black")) setBackground(Color.BLACK); if(s.equals("Yellow")) setBackground(Color.YELLOW); if(s.equals("Green")) setBackground(Color.GREEN); repaint();

public void itemStateChanged(ItemEvent event){ } public void actionPerformed(ActionEvent event){ } }

69

Các thành phần khác

o Một số thành phần khác như: TextArea (vùng văn bản), Menu (thực đơn), ScrollBar (thanh trượt), Canvas (khung vẽ), Applet,… sẽ được trình bày ở các chương sau.

Các đối tượng khung chứa

o Là các thành phần mà có thể chứa các thành phần

khác, có thể vẽ và tô màu.

o Gồm có: Frame, Applet, Panel, ScrollPane, Dialog,

FileDialog.

Cách tính tọa độ

screen screen

y

x

screen height

height

MyWindow

width

screen width

Khung chứa Frame

o Frame được dùng để xây dựng các ứng dụng GUI

chạy độc lập.

o Frame là một cửa sổ có thanh tiêu đề và các đường biên. Bố cục mặc định của Frame là BorderLayout. o Frame kế thừa từ Window, nó có thể nghe các sự kiện

xảy ra trên cửa sổ khi cài đặt giao tiếp WindowListener.

o Các ứng dụng độc lập thường tạo ra cửa sổ kế thừa từ

lớp Frame.

import java.awt.*; importjava.awt.event.*; public class DemoFrame{ public static void main(String[] args){

Frame frame = new Frame(“Example on Frame”); Labellabel = newLabel("This is a label in

frame.add(label, BorderLayout.CENTER); frame.setSize(500,500); frame.setVisible(true); frame.addWindowListener(newMyWindowListener());

Frame",Label.CENTER); }

System.exit(0);

}

} // Lop nghe doc lap (external listener) Class MyWindowListener extendsWindowAdapter{ public void windowClosing(WindowEvent event){ }

74

System.exit(0);

public void windowClosing(WindowEvent e){ }

myFrame.setSize(250, 300); myFrame.setVisible(true); myFrame.addWindowListener(newWindowAdapter() { // Lop nghe noi khong ten (anonymous inner class listener) });

import java.awt.*; Import java.awt.event.*; public class DemoFrame2{ public static void main(String[] args){ MyFrame myFrame = new MyFrame("Example on my frame"); } } //xem tiếp ở slide tiếp theo

75

super(title);

public MyFrame(String title){

Class MyFrame extends Frame{ } public void paint(Graphics g){ g.setColor(Color.BLUE); g.fillOval(40, 40, 80, 80); } }

76

Lớp Panel (vùng chứa)

o Lớp Panel kế thừa từ Container. Nó có thể được dùng để

tạo ra các giao diện theo ý muốn.

o Ví dụ: Một giao diện có thể có nhiều panel sắp xếp theo

một layout nhất định, mỗi panel lại có các component sắp xếp theo một layout riêng.

o Chú ý: Panel có bố cục mặc định là FlowLayout.

Panel(BorderLayout) Panel(BorderLayout)

TextField

Button

12 Button

Frame(BorderLayout) Frame(BorderLayout)

Panel(GridLayout) Panel(GridLayout)

this.setLayout(new BorderLayout()); this.add(choice, BorderLayout.NORTH); this.add(panel, BorderLayout.CENTER);

public void init(){ Choice choice = new Choice(); choice.add("Red"); choice.add("Green"); choice.add("Blue"); Button ok = new Button("Ok"); Button cancel = new Button("Cancel"); Panel panel = new Panel(); panel.add(ok); panel.add(cancel); }

78

Các đối tượng khung chứa khác

o Scroll pane: Thanh cuộn o Dialog: hộp thoại