ươ

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

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ự

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

– Listener là một giao diện (interface); Chúng ta

kiện

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

tạo ra một Listener bằng cách thực thi (implementing) giao diện đó

tham số

Giới thiệu AWT

o AWT(Abstract Window Toolkit) là t p h p các l p

ế ế ộ ỗ ợ ậ ớ ự t k , xây d ng m t GUI

ấ java cung c p h  tr  thi (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

ề ứ ủ ụ ạ

ể ượ ị ở c đ nh nghĩa b i chính

ề ử ụ o S  d ng các đi u khi n đ ủ ạ ệ ề 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

o Dễ dàng tạo các giao diện đẹp

o Gói cần sử dụng: javax.swing.*;

linh hoạt hơn

So sánh AWT và Swing

o Swing phong phú hơn, chậm hơn và phức tạp

§ 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ỉ

hơn

o Swing thêm J vào trước các điều khiển của AWT:

o VD:

có thể sử dụng 1 trong 2.

AWT:   Button b = new Button ("OK");

Swing: JButton b = new JButton("OK");

Tạo một GUI

Các Component của GUI

o Container:

ộ ứ § B  ch a.

§ Các Component th

ườ ng dùng là: TextFields,

o Component:

§ Các thành phần giao diện.

§ Các bộ chứa thường sử dụng là Panel (và

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

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

Applet), Window, và Frame

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

Component.

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

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

Tạo một Container

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

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  ươ

ỉ ệ ọ

ng th c setLayout(

ộ null) v i ớ

container ta ch  vi c g i ph tham s  là ố null.

ng Component dùng

ư

ừ ượ c c a component khi đ a

ể ự

ứ ủ ớ ộ ố ươ ng th c c a l p tr u t o M t s  ph ướ ủ ị ị ể ị đ  đ nh v  và qui đ nh kích th 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)

o Ví dụ:

­ MyButton.setSize(new Dimension(20, 10));

­ MyButton.setLocation(new Point(10, 10));

­ MyButton.setBounds(10, 10, 20, 10);

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

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);

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

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

JCheckBox(“Nam”);

o JCheckBox – checkbox

o JComboBox – danh sách thả

khác

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()

§ JLabel(String labeltext)

§ JLabel(String labeltext, int alignment)

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

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

§ 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

o Các nút nhấn trên giao diện

o Các hàm dựng:

§ JButton()

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

JCheckBoxes/JRadioButtons

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

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

mục 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

một mục duy nhất trong nhóm

§ Chỉ ra vị trí trên màn hình

§ Hiển thị ra màn hình

hay unselected)

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

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

JComboBox();

o Thêm JComboBox vào container

o Các phương thức

§ getItemCount().

§ getItemAt(int).

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

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:

§ position là NORTH, SOUTH, EAST, WEST

container.add(component, BorderLayout.position);

§ N u đ t  ế th  2ứ

ặ ở ữ ầ ố  gi a (CENTER) thì không c n tham s

Tạo các listener

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 {

public void actionPerformed(ActionEvent event) {

ử ạ // Đo n mã x  lý

}

}

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ý

}

}

v 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)ừ

class SomeClass {

JFrame frame;

JButton button;

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

public static void main(String[] args) {

new SomeClass().createGui();

ộ ớ

ể ử

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

}

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)

class SomeClass extends JFrame {

// JFrame frame; // Don't need this

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

JButton button;

public static void main(String[] args) {

ộ ớ

ể ử

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

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(DocumentList

ener)

• 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

§ Enabled = true: Kích hoạt,

§ Enabled = false: Vô hiệu hóa

anyComponent.setEnabled(enabled);

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

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

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

o

của JOptionPane

“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

o

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

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",

o

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

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à:

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

JOptionPane.YES_NO_CANCEL_OPTION

o Tham số thứ 6 (null ở trên) có thể xác định một

thoại ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, hoặc PLAIN_MESSAGE

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_O

o Các tùy chọn khác:

N_CLOSE);

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)

import java.applet.Applet;

import java.awt.*;

public class DemoLabel extends Applet{

private Label label;

public void init(){

Font font = new Font("Courier", Font.BOLD, 20);

ươ

label = new Label(“Ch

ầ ng trình đ u tiên");

label.setFont(font);

add(label);

}

public void paint(Graphics g){

showStatus("N i dung c a label: “ + label.getText());

}

}

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

§ TextField(...); // các c u tấ ử

ộ ố ươ ứ ng th c

§ void setEditable(boolean b); // đ t/t

ặ ắ ế ộ t ch  đ

nh pậ

§ void setEchoChar(char c); // đ t kí t

ặ ự ể ị hi n th

o Đ i t

§ ActionListener

§ TextListener

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

• 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{

private TextField txtEdit; private TextField txtReadOnly; private TextField txtPass; private final String PASSWORD = "Java"; public void init(){

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

ế ở

// xem ti p

ế ế  slide k  ti p

56

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

} public void actionPerformed(ActionEvent event){ if(txtPass.getText().equals(PASSWORD))

txtReadOnly.setText("Password is valid");

else

txtReadOnly.setText("Invalid password !");

}

}

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

§ Choice(); // c u tấ ử

§ void addItem(String s); // thêm item là s

ộ ố ươ ứ ng th c

§ 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{

private Choice choice; private TextField txtText; private Font font; public void init(){

choice = newChoice(); choice.addItem("TimesRoman"); choice.addItem("Courier"); choice.addItem("Helvetica"); choice.addItemListener(this); ế ế ế ở  slide k  ti p

// xem 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);

} public void itemStateChanged(ItemEvent event){

font = newFont(choice.getSelectedItem(), Font.PLAIN,

12);

txtText.setFont(font);

}

}

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

§ Checkbox(...); // các c u tấ ử

ộ ố ươ ứ ng th c

§ 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(...)

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(){

ế ở

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);\ ế ế  slide k  ti p

//xem ti p

62

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

} public void itemStateChanged(ItemEvent event){

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);

}

}

63

Check Box Group & Radio Button

ộ c đ t trong m t

ộ ể

ộ ỗ

ượ

o Víd : ụ T o 3 radio button thu c cùng m t nhóm. Ban  ể ờ ạ c ch n. T i m i th i đi m ch  có th

ầ ọ

đ u radio1 đ ch n m t  trong 3 radio.

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 Các Checkboxcó th  đ ể ạ CheckboxGroup đ  t o ra các Radio Button.

// Cac import can thiet... public class DemoRadio extends Applet implements ItemListener{

private Checkbox plain, bold, italic; private CheckboxGroup group; private TextFieldtxtText; public void init(){

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);

ế ở

//xem ti p

ế  slide ti p theo

65

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

} public void itemStateChanged(ItemEvent event){

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));

}

}

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{

private List colorList; public void init(){

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

} ế ở

//xem ti p

ế  slide ti p theo

68

public void itemStateChanged(ItemEvent event){

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

selected"); } public void actionPerformed(ActionEvent event){

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();

}

}

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

ư

ẽ ượ ượ t),  c trình bày ở

ươ ầ ộ ố ự ơ ả b n), Menu (th c đ n), ScrollBar (thanh tr ẽ Canvas (khung v ), Applet,… s  đ 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

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",Label.CENTER);

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

}

} // Lop nghe doc lap (external listener) Class MyWindowListener extendsWindowAdapter{

public void windowClosing(WindowEvent event){

System.exit(0);

}

74

}

import java.awt.*; Import java.awt.event.*; public class DemoFrame2{

public static void main(String[] args){   MyFrame myFrame = new MyFrame("Example on my

frame");

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

listener)

public void windowClosing(WindowEvent e){

System.exit(0);

}

});

}

75

ế ở

} //xem ti p

ế  slide ti p theo

Class MyFrame extends Frame{

public MyFrame(String title){

super(title);

} 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

c dùng

ế ừ ừ  Container. Nó có th  đ ố ệ

ớ ể ạ

đ  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

ề i có các component

ế

ấ ị ộ m t layout nh t đ nh, m i panel l ộ ắ s p x p theo m t layout riêng.

ặ ị

ố ụ

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

Panel(BorderLayout )

TextField

Button

12 Button

Frame(BorderLayout )

Panel(GridLayout )

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); this.setLayout(new BorderLayout()); this.add(choice, BorderLayout.NORTH); this.add(panel, BorderLayout.CENTER);

}

78

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

o Scroll pane: Thanh cu n ộ

ạ o Dialog: h p tho i