34
I,Tổng quan về Swing. Nếu bạn đã từng vào trang chủ của Java (http://oracle.com/java), bạn sẽ nhìn thấy Swing được mô tả như là một tập các thành phần đồ họa được tạo ra để những cảm quan (Look&Feel) được thể hiện vào thời điểm runtime. Thật sự, thì Swing còn nhiều hơn như thế. Swing là bộ công cụ GUI thế hệ kế tiếp mà Sun Microsystems tạo ra cho phép môi trường phát triển enterprise trong Java.Bằng môi trường phát triển enterprise, chúng ta hiểu rằng, các lập trình viên có thể sử dụng Swing để tạo ra các ứng dụng Java có khả năng mở rộng với một dãy nhiều thành phần mạnh mẽ. Thêm vào đó, bạn có thể kế thừa hoặc chỉnh sửa những thành phần này để điều khiển việc hiển thị và các hành xử của chúng. Swing không phải là một từ viết tắt. Đó là tên thay thế cho một tập hợp lựa chọn của nó cho các designer khi dự án được thực hiện vào 1996. Swing thật sự là một phần của gia đình rộng lớn các sản phẩm của Java được biết đến như Java Foundation Classes s(JFC) bao gồm nhiều đặc điểm của Internet Foundation Classes của Netscape cũng như bị ảnh hưởng thiết kế của Taligent và Lighthouse Design của IBM. Swing được phát triển thật 1 | Page

Lập trình giao diện Swing trong java

Embed Size (px)

DESCRIPTION

tìm hiểu về lập trình SWing trong java

Citation preview

Page 1: Lập trình giao diện Swing trong java

I,Tổng quan về Swing.

Nếu bạn đã từng vào trang chủ của Java (http://oracle.com/java), bạn sẽ

nhìn thấy Swing được mô tả như là một tập các thành phần đồ họa được tạo ra để

những cảm quan (Look&Feel) được thể hiện vào thời điểm runtime.

Thật sự, thì Swing còn nhiều hơn như thế. Swing là bộ công cụ GUI thế hệ kế tiếp

mà Sun Microsystems tạo ra cho phép môi trường phát triển enterprise trong

Java.Bằng môi trường phát triển enterprise, chúng ta hiểu rằng, các lập trình viên

có thể sử dụng Swing để tạo ra các ứng dụng Java có khả năng mở rộng với một

dãy nhiều thành phần mạnh mẽ. Thêm vào đó, bạn có thể kế thừa hoặc chỉnh sửa

những thành phần này để điều khiển việc hiển thị và các hành xử của chúng.

Swing không phải là một từ viết tắt. Đó là tên thay thế cho một tập hợp lựa

chọn của nó cho các designer khi dự án được thực hiện vào 1996. Swing thật sự là

một phần của gia đình rộng lớn các sản phẩm của Java được biết đến như Java

Foundation Classes s(JFC) bao gồm nhiều đặc điểm của Internet Foundation

Classes của Netscape cũng như bị ảnh hưởng thiết kế của Taligent và Lighthouse

Design của IBM. Swing được phát triển thật sự kể từ thời điểm bản beta của JDK

1.1, khoảng mùa xuân 1997. Swing API bản beta đưa ra khoảng nửa cuối 1997 và

được chính thức phát hành vào tháng 3 năm 1998. Khi được phát hành, các thư

viện của Swing 1.0 chứa khoảng 250 lớp và 80 giao tiếp. Sự phát triển được tiếp

tục khi theo thời gian, bản Swing 1.4 chứa 85 giao tiếp public và 451 lớp

public.Mặc dù Swing là được phát triển đơn lẻ từ lõi của Java Development Kit, nó

yêu cầu phải có tối thiểu JDK 1.1.5 để chạy. Swing được xây dựng dựa trên những

mô hình event được giới thiệu trong serie JDK 1.1. Bạn không thể sử dụng Swing

với JDK 1.0.2, thêm vào đó bạn phải có Java 1.1 cho phép trình duyệt hỗ trợ Swing

Applet. Java 2 SDK 1.4 được phát hành bao gồm nhiều lớp Swing được cập nhật

và hỗ trợ một vài đặc điểm mới. Swing được tích hợp đầy đủ trong cả trong bộ

công cụ của các nhà phát triển và runtime environment của tất cả các bản phát hành 1 | P a g e

Page 2: Lập trình giao diện Swing trong java

Java 2 (SDK 1.2 và những phiên bản cao hơn) chứa cả Java Plug-in.Cho đến nay

dù java đã rất lâu từ khi java ra đời nó vẫn là ngô ngữ phổ biến của giới lập trình.

Hình 1:Giao diện swing đơn giản

II,Các thành phần giao tiếp cơ bản của swing.

1,Các container .

1.1.Jframe.

JFrame là một Top-level Container thường được sử dụng để tạo các giao diện

ứng dụng người dùng.Nó thường được dùng để chứa các thành phần giao diện khác

( Button, Label, … ).

1.2.JPanel.

JPanel là một container (thùng chứa) nó dùng để chứa các đối tượng tương tự

như JFrame tuy nhiên nó không phải là 1 JFrame.

2,Các Components.

2 | P a g e

Page 3: Lập trình giao diện Swing trong java

2.1.Jlaybel.

2.2.JButton.

2.3.JCheckBox .

2.4.JTextField.

2.5.JTextArea.

3,Các thành phần khác.

3.1.JCombobox.

JCombobox giống như một drop down box – bạn có thể click vào mũi tên

drop down và chọn một lựa chọn từ một danh sách. Nó sinh ra ItemEvent.Thanh

cuộn dọc thường được dùng cho một danh sách dài.

Hình 2:Demo Combobox

Khai báo ComboBox như sau:

3 | P a g e

Page 4: Lập trình giao diện Swing trong java

Hàm khởi tạo Combobox

JComboBox()

JComboBox(ComboBoxModel)

JComboBox(Object[])

JComboBox(Vector)

3.2.JSlider.

Một thành phần JSlider được thiết kế để cho phép người dùng dễ dàng nhập một giá trị số giới hạn bởi một giá trị tối thiểu và tối đa..Thanh trượt của slider có thể tùy biến nằm ngang hoặc nằm dọc. Và chúng ta sẽ thấy các giá trị được biểu diễn trên một thanh trượt như sau

4 | P a g e

Page 5: Lập trình giao diện Swing trong java

Hình 3:Demo Jslider

Khai báo JSlider như sau:

public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); if (!source.getValueIsAdjusting()) { int fps = (int)source.getValue(); if (fps == 0) { if (!frozen) stopAnimation(); } else { delay = 1000 / fps; timer.setDelay(delay); timer.setInitialDelay(delay * 10); if (frozen) startAnimation(); } }}

Hàm khởi tạo (contructor) của Jslider:

JSlider()

JSlider(int min, int max)

JSlider(int orientation)

JSlider(BoundedRangeModel)

5 | P a g e

Page 6: Lập trình giao diện Swing trong java

3.3JRadioButton.

Nút radio là nhóm các nút, trong đó, theo quy ước, chỉ có một nút tại một thời

điểm có thể được lựa chọn.Dưới đây là mã từ RadioButtonDemo.java tạo ra các nút

radio trong ví dụ trước và phản ứng với nhấp chuột.

JRadioButton birdButton = new JRadioButton(birdString); birdButton.setMnemonic(KeyEvent.VK_B); birdButton.setActionCommand(birdString); birdButton.setSelected(true);

JRadioButton catButton = new JRadioButton(catString); catButton.setMnemonic(KeyEvent.VK_C); catButton.setActionCommand(catString);

JRadioButton dogButton = new JRadioButton(dogString); dogButton.setMnemonic(KeyEvent.VK_D); dogButton.setActionCommand(dogString);

JRadioButton rabbitButton = new JRadioButton(rabbitString); rabbitButton.setMnemonic(KeyEvent.VK_R); rabbitButton.setActionCommand(rabbitString);

JRadioButton pigButton = new JRadioButton(pigString); pigButton.setMnemonic(KeyEvent.VK_P); pigButton.setActionCommand(pigString);

//Group the radio buttons. ButtonGroup group = new ButtonGroup(); group.add(birdButton); group.add(catButton); group.add(dogButton); group.add(rabbitButton); group.add(pigButton);

//Register a listener for the radio buttons. birdButton.addActionListener(this); catButton.addActionListener(this); dogButton.addActionListener(this); rabbitButton.addActionListener(this); pigButton.addActionListener(this);...public void actionPerformed(ActionEvent e) { picture.setIcon(new ImageIcon("images/" + e.getActionCommand() + ".gif"));}6 | P a g e

Page 7: Lập trình giao diện Swing trong java

3.4.Jlist.

Một JList hiện cho người dùng với một nhóm sản phẩm, hiển thị trong một

hoặc nhiều cột, để lựa chọn. Danh sách có thể có nhiều mặt hàng, do đó chúng

thường được đặt trong tấm di chuyển. Ngoài danh sách, các thành phần Swing sau

đây giới thiệu nhiều mặt hàng có thể lựa chọn cho người sử dụng: hộp tổ hợp, trình

đơn, bảng biểu, và nhóm các hộp kiểm tra hoặc nút radio. Để hiển thị dữ liệu phân

cấp, sử dụng một Tree.

Hình 4:Demo Jlist

Demo khai báo Jlist

list = new JList(data); //data has type Object[]list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);list.setLayoutOrientation(JList.HORIZONTAL_WRAP);list.setVisibleRowCount(-1);...JScrollPane listScroller = new JScrollPane(list);listScroller.setPreferredSize(new Dimension(250, 80));

3.5 JTable.

Với lớp JTable bạn có thể hiển thị bảng dữ liệu, tùy chọn cho phép người

dùng chỉnh sửa dữ liệu. JTable không chứa dữ liệu hoặc bộ nhớ cache; nó chỉ đơn

giản là một cách biểu diễn dữ liệu của bạn.

7 | P a g e

Page 8: Lập trình giao diện Swing trong java

Hình 5:Demo Jtable

Theo mặc định, tất cả các cột trong một bảng bắt đầu với chiều rộng bằng

nhau, và các cột tự động điền vào toàn bộ chiều rộng của bảng. Khi bảng trở nên

rộng hơn hoặc hẹp hơn (có thể xảy ra khi người dùng thay đổi kích thước cửa sổ

chứa bảng), tất cả các độ rộng cột thay đổi thích hợp. Khi người dùng thay đổi kích

thước một cột bằng cách kéo biên phải của mình, sau đó một trong hai cột khác

phải thay đổi kích thước, hoặc kích thước của bảng phải thay đổi. Theo mặc định,

kích thước của bảng vẫn giữ nguyên, và tất cả các cột bên phải của điểm kéo thay

đổi kích thước để phù hợp không gian thêm vào hoặc gỡ bỏ từ cột bên trái của điểm

kéo. Để tùy chỉnh độ rộng cột ban đầu, bạn có thể gọi setPreferredWidth trên mỗi

cột của bảng của bạn. Điều này đặt ra cả chiều rộng ưa thích của các cột và chiều

rộng tương đối gần đúng của họ. Ví dụ, thêm đoạn mã sau vào SimpleTableDemo

làm cho cột thứ ba của nó lớn hơn các cột khác:

TableColumn column = null;for (int i = 0; i < 5; i++) { column = table.getColumnModel().getColumn(i); if (i == 2) { column.setPreferredWidth(100); //third column is bigger } else { column.setPreferredWidth(50); }}

8 | P a g e

Page 9: Lập trình giao diện Swing trong java

Để tạo một bảng mẫu trong Swing ta làm như sau.

new AbstractTableModel() {

public String getColumnName(int col) { return columnNames[col].toString(); } public int getRowCount() { return rowData.length; } public int getColumnCount() { return columnNames.length; } public Object getValueAt(int row, int col) { return rowData[row][col]; } public boolean isCellEditable(int row, int col) { return true; } public void setValueAt(Object value, int row, int col) { rowData[row][col] = value; fireTableCellUpdated(row, col); }}

Lớp sự kiện của Jtable là TablemoderListener chúng ta hãy theo dõi demo sau đây

import javax.swing.event.*;import javax.swing.table.TableModel;

public class SimpleTableDemo ... implements TableModelListener { ... public SimpleTableDemo() { ... table.getModel().addTableModelListener(this); ... }

public void tableChanged(TableModelEvent e) { int row = e.getFirstRow();

9 | P a g e

Page 10: Lập trình giao diện Swing trong java

int column = e.getColumn(); TableModel model = (TableModel)e.getSource(); String columnName = model.getColumnName(column); Object data = model.getValueAt(row, column);

...// Do something with the data... } ...}

Chúng ta có thể tạo một bảng trong đó kết hợp giữa Jtable với combobox hay

với các thành phần khác được trình bày ở phần trước.Hãy cùng nhau xem xét các ví

dụ sau:

Ex1:

TableColumn sportColumn = table.getColumnModel().getColumn(2);...JComboBox comboBox = new JComboBox();comboBox.addItem("Snowboarding");comboBox.addItem("Rowing");comboBox.addItem("Chasing toddlers");comboBox.addItem("Speed reading");comboBox.addItem("Teaching high school");comboBox.addItem("None");sportColumn.setCellEditor(new DefaultCellEditor(comboBox));

Ex2:public class ColorEditor extends AbstractCellEditor

implements TableCellEditor, ActionListener { Color currentColor;

10 | P a g e

Page 11: Lập trình giao diện Swing trong java

JButton button; JColorChooser colorChooser; JDialog dialog; protected static final String EDIT = "edit";

public ColorEditor() { button = new JButton(); button.setActionCommand(EDIT); button.addActionListener(this); button.setBorderPainted(false);

//Set up the dialog that the button brings up. colorChooser = new JColorChooser(); dialog = JColorChooser.createDialog(button, "Pick a Color", true, //modal colorChooser, this, //OK button handler null); //no CANCEL button handler }

public void actionPerformed(ActionEvent e) { if (EDIT.equals(e.getActionCommand())) { //The user has clicked the cell, so //bring up the dialog. button.setBackground(currentColor); colorChooser.setColor(currentColor); dialog.setVisible(true);

fireEditingStopped(); //Make the renderer reappear.

} else { //User pressed dialog's "OK" button. currentColor = colorChooser.getColor(); } }

11 | P a g e

Page 12: Lập trình giao diện Swing trong java

3.6 JTree.

Với lớp JTree, bạn có thể hiển thị dữ liệu phân cấp. Một đối tượng JTree

không thực sự chứa dữ liệu của bạn; nó chỉ đơn giản là biểu diễn của dữ liệu.

Giống như bất kỳ thành phần Swing , cây được dữ liệu bằng cách truy vấn mô hình

dữ liệu của nó. Đây là một hình ảnh của một cây:

Hình 6:Mô hình Tree

JTree hiển thị dữ liệu theo chiều dọc. Mỗi hàng hiển thị bởi các cây chứa chính xác một mục dữ liệu, được gọi là một nút(Node). Mỗi cây có một nút gốc mà từ đó tất cả các nút đi xuống. Theo mặc định, cây hiển thị các nút gốc, nhưng bạn

12 | P a g e

Page 13: Lập trình giao diện Swing trong java

có thể chỉ định nút khác. Một nút có thể hoặc có con hay không.Chúng ta cùng nhau xem qua đoạn demo về Tree sau:

private JTree tree;...public TreeDemo() { ... DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series"); createNodes(top); tree = new JTree(top); ... JScrollPane treeView = new JScrollPane(tree); ...}

Code này tạo một một nút gốc cho cây.Sau đó nó tạo ra các nút còn lại của

cây,các nút gốc được xác định bằng tham số,cuối cùng nó đặt cây trong một cửa

sổ,chúng ta có thể click để xổ ra các thư mục từ cây.Cây được biểu diễn trong các

hệ điều hành có thể khác nhau về đồ họa nhưng bản chất nó không có gì thay đổi.

Khởi tạo một cây thư mục như sau:

rootNode = new DefaultMutableTreeNode("Root Node");treeModel = new DefaultTreeModel(rootNode);treeModel.addTreeModelListener(new MyTreeModelListener());

tree = new JTree(treeModel);tree.setEditable(true);tree.getSelectionModel().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION);tree.setShowsRootHandles(true);

13 | P a g e

Page 14: Lập trình giao diện Swing trong java

Nếu DefaultTreeModel không phù hợp với nhu cầu của bạn, bạn sẽ cần phải

viết một mô hình dữ liệu tùy chỉnh. Mô hình dữ liệu của bạn phải thực hiện giao

diện TreeModel. TreeModel quy định cụ thể phương pháp để có được một nút cụ

thể của cây, nhận được số lượng con cháu của một nút cụ thể, xác định một nút là

một chiếc lá, thông báo cho các mô hình của một sự thay đổi trong cây, và thêm và

loại bỏ các mô hình giả hoặc cũ trong cây. Thật thú vị, giao diện TreeModel chấp

nhận bất kỳ loại đối tượng như là một nút cây. Nó không đòi hỏi rằng các nút được

biểu diễn bởi các đối tượng DefaultMutableTreeNode, hoặc thậm chí là các nút

thực hiện giao diện TreeNode. Ví dụ, nếu bạn có một cấu trúc dữ liệu phân cấp từ

trước, bạn không cần phải lặp lại nó hay buộc nó vào khuôn TreeNode. Bạn chỉ cần

thực hiện mô hình cây của bạn để nó sử dụng các thông tin trong cấu trúc dữ liệu

hiện có.

III,Layout Manager

Layout là những phương thức sắp xếp các component trong các container.Để

thiết lập layout cho container chúng ta làm như sau:

import java.awt.*;

    class Fltest extends Frame

    {

    Button b1=new Button("Center Aligned Button 1");

    Button b2=new Button("Center Aligned Button 2");

    Button b3=new Button("Center Aligned Button 3");   

    public Fltest(String title)

    {

    super(title);

    setLayout(new FlowLayout(FlowLayout.CENTER));

14 | P a g e

Page 15: Lập trình giao diện Swing trong java

    add(b1);

    add(b2);

    add(b3);

    }   

    public static void main(String args[])

    {

    Fltest t=new Fltest("Flow Layout");

    t.setSize(300,200);

    t.show();

    }

    }

   

1.FlowLayout.

Các component hiển thị từ trái sang phải,từ trên xuống dưới bên trong container theo đúng thứ tự được add của chúng.Khi hết một dòng sẽ xuống dòng mới tiếp theo.

Hình 7:FlowLayout

2.BorderLayout.15 | P a g e

Page 16: Lập trình giao diện Swing trong java

Container được chia làm 5 vùng theo các hướng:đông,tây,nam,bắc,trung tâm.

Hình 8:BorderLayout

3.GridbagLayout.

Các Component được thêm vào dựa theo tọa độ mà chúng ta truyền vào.

Hình 9:GridbagLayout

IV,Xử lý sự kiện trong Swing.

Sự kiện là sự tương tác của người dùng và phần mềm phải có sự phản hồi

lại,sự tương tác có thể là một cú click chuột,nhấn phím,chọn trong danh sách….Khi

bắt sự kiện phải chỉ ra đấy là sự kiện nào và của cái gì.

Một số xử lý sự kiện đơn giản.

16 | P a g e

Page 17: Lập trình giao diện Swing trong java

Ex1:sự kiện của các nut bấm

public class MultiListener ... implements ActionListener { ... //where initialization occurs: button1.addActionListener(this); button2.addActionListener(this);

button2.addActionListener(new Eavesdropper(bottomTextArea)); }

public void actionPerformed(ActionEvent e) { topTextArea.append(e.getActionCommand() + newline); }}

class Eavesdropper implements ActionListener { ... public void actionPerformed(ActionEvent e) { myTextArea.append(e.getActionCommand() + newline); }}

Các sự kiện và listener tương ứng:

1ActionEvent- ActionListener

ActionListener có lẽ là dễ nhất - xử lý sự kiện để thực hiện - và phổ biến nhất. Máy tính thực hiện một hành động lắng nghe để xác định những gì nên được thực hiện khi người dùng thực hiện một hoạt động nhất định. Bây giờ, khi người dùng nhấp vào nút b, nút bị ấn sinh ra một sự kiện mà hành động gọi phương thức

17 | P a g e

Page 18: Lập trình giao diện Swing trong java

actionPerformed. Mỗi khi người dùng nhấn nút,hành động này sẽ được bắt bởi ActionListener.Ví dụ:

import java.awt.*;import java.awt.event.*;

public class AL extends Frame implements WindowListener,ActionListener { TextField text = new TextField(20); Button b; private int numClicks = 0;

public static void main(String[] args) { AL myWindow = new AL("My first window"); myWindow.setSize(350,100); myWindow.setVisible(true); }

public AL(String title) {

super(title); setLayout(new FlowLayout()); addWindowListener(this); b = new Button("Click me"); add(b); add(text); b.addActionListener(this); }

public void actionPerformed(ActionEvent e) { numClicks++; text.setText("Button Clicked " + numClicks + " times"); }

public void windowClosing(WindowEvent e) { dispose(); System.exit(0); }

public void windowOpened(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowClosed(WindowEvent e) {}

}

18 | P a g e

Page 19: Lập trình giao diện Swing trong java

2.ForcusEvent – FocusListener

Đây là sự kiện khi chuột hay phím cần tập trung vào một điểm nào đó lúc này sẽ máy tính sẽ gọi đến phương thức FocusListener để tập trung cho một giao diện duy nhất.Ví dụ khi bạn cần đăng ký tài khoản con trỏ chuột luôn nháy ở ô đăng ký đầu tiên,đúng không?Sau đây là Demo của FocusListener:

public class FocusEventDemo ... implements FocusListener ... { public FocusEventDemo() { ... JTextField textField = new JTextField("A TextField"); textField.addFocusListener(this); ... JLabel label = new JLabel("A Label"); label.addFocusListener(this); ... JComboBox comboBox = new JComboBox(vector); comboBox.addFocusListener(this); ... JButton button = new JButton("A Button"); button.addFocusListener(this); ... JList list = new JList(listVector); list.setSelectedIndex(1); //It's easier to see the focus change //if an item is selected. list.addFocusListener(this); JScrollPane listScrollPane = new JScrollPane(list); ...

//Set up the area that reports focus-gained and focus-lost events. display = new JTextArea(); display.setEditable(false); //The method setRequestFocusEnabled prevents a //component from being clickable, but it can still //get the focus through the keyboard - this ensures //user accessibility. display.setRequestFocusEnabled(false); display.addFocusListener(this); JScrollPane displayScrollPane = new JScrollPane(display);

... } ... public void focusGained(FocusEvent e) { displayMessage("Focus gained", e); }

19 | P a g e

Page 20: Lập trình giao diện Swing trong java

public void focusLost(FocusEvent e) { displayMessage("Focus lost", e); }

void displayMessage(String prefix, FocusEvent e) { display.append(prefix + (e.isTemporary() ? " (temporary):" : ":") + e.getComponent().getClass().getName() + "; Opposite component: " + (e.getOppositeComponent() != null ? e.getOppositeComponent().getClass().getName() : "null") + newline); } ...}

3.ItemEvent – ItemListener

Nhìn chung đây là sự kiện lien quan đến các mục được chọn như checkbox,Checkmenu Item,combobox…sau đây là demo về itemEvent – ItemListener

//where initialization occurscheckbox.addItemListener(this);...public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { label.setVisible(true); ... } else { label.setVisible(false); }}

4.WindowEvent – WindowListener

Đây là các loại sự kiện lien quan đến cửa sổ(Hộp thoại…).Đây là demo về WindowEvent – WindowListener

public class WindowEventDemo extends JFrame implements WindowListener, WindowFocusListener, WindowStateListener { ... static WindowEventDemo frame = new WindowEventDemo("WindowEventDemo"); JTextArea display;

20 | P a g e

Page 21: Lập trình giao diện Swing trong java

...

private void addComponentsToPane() { display = new JTextArea(); display.setEditable(false); JScrollPane scrollPane = new JScrollPane(display); scrollPane.setPreferredSize(new Dimension(500, 450)); getContentPane().add(scrollPane, BorderLayout.CENTER); addWindowListener(this); addWindowFocusListener(this); addWindowStateListener(this); checkWM(); } public WindowEventDemo(String name) { super(name); }

//Some window managers don't support all window states. public void checkWM() { Toolkit tk = frame.getToolkit(); if (!(tk.isFrameStateSupported(Frame.ICONIFIED))) { displayMessage( "Your window manager doesn't support ICONIFIED."); } else displayMessage( "Your window manager supports ICONIFIED."); if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_VERT))) { displayMessage( "Your window manager doesn't support MAXIMIZED_VERT."); } else displayMessage( "Your window manager supports MAXIMIZED_VERT."); if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_HORIZ))) { displayMessage( "Your window manager doesn't support MAXIMIZED_HORIZ."); } else displayMessage( "Your window manager supports MAXIMIZED_HORIZ."); if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_BOTH))) { displayMessage( "Your window manager doesn't support MAXIMIZED_BOTH."); } else { displayMessage( "Your window manager supports MAXIMIZED_BOTH."); } }

public void windowClosing(WindowEvent e) {

21 | P a g e

Page 22: Lập trình giao diện Swing trong java

displayMessage("WindowListener method called: windowClosing."); //A pause so user can see the message before //the window actually closes. ActionListener task = new ActionListener() { boolean alreadyDisposed = false; public void actionPerformed(ActionEvent e) { if (frame.isDisplayable()) { alreadyDisposed = true; frame.dispose(); } } }; Timer timer = new Timer(500, task); //fire every half second timer.setInitialDelay(2000); //first delay 2 seconds timer.setRepeats(false); timer.start(); }

public void windowClosed(WindowEvent e) { //This will only be seen on standard output. displayMessage("WindowListener method called: windowClosed."); }

public void windowOpened(WindowEvent e) { displayMessage("WindowListener method called: windowOpened."); }

public void windowIconified(WindowEvent e) { displayMessage("WindowListener method called: windowIconified."); }

public void windowDeiconified(WindowEvent e) { displayMessage("WindowListener method called: windowDeiconified."); }

public void windowActivated(WindowEvent e) { displayMessage("WindowListener method called: windowActivated."); }

public void windowDeactivated(WindowEvent e) { displayMessage("WindowListener method called: windowDeactivated."); }

public void windowGainedFocus(WindowEvent e) { displayMessage("WindowFocusListener method called: windowGainedFocus."); }

public void windowLostFocus(WindowEvent e) { displayMessage("WindowFocusListener method called: windowLostFocus.");

22 | P a g e

Page 23: Lập trình giao diện Swing trong java

}

public void windowStateChanged(WindowEvent e) { displayStateMessage( "WindowStateListener method called: windowStateChanged.", e); }

void displayMessage(String msg) { display.append(msg + newline); System.out.println(msg); }

void displayStateMessage(String prefix, WindowEvent e) { int state = e.getNewState(); int oldState = e.getOldState(); String msg = prefix + newline + space + "New state: " + convertStateToString(state) + newline + space + "Old state: " + convertStateToString(oldState); displayMessage(msg); }

String convertStateToString(int state) { if (state == Frame.NORMAL) { return "NORMAL"; } String strState = " "; if ((state & Frame.ICONIFIED) != 0) { strState += "ICONIFIED"; } //MAXIMIZED_BOTH is a concatenation of two bits, so //we need to test for an exact match. if ((state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) { strState += "MAXIMIZED_BOTH"; } else { if ((state & Frame.MAXIMIZED_VERT) != 0) { strState += "MAXIMIZED_VERT"; } if ((state & Frame.MAXIMIZED_HORIZ) != 0) { strState += "MAXIMIZED_HORIZ"; } if (" ".equals(strState)){ strState = "UNKNOWN"; } } return strState.trim();

23 | P a g e

Page 24: Lập trình giao diện Swing trong java

}}

5.MouseEvent – MouseListener

Sự kiện chuột thông báo khi người dùng sử dụng chuột (hoặc thiết bị đầu vào tương tự) để tương tác với một thành phần. Sự kiện chuột xảy ra khi con trỏ đi vào hoặc thoát ra khỏi khu vực trên màn hình và khi người dùng nhấn phím một trong các nút chuột.Demo của MouseEvent:

public class MouseEventDemo ... implements MouseListener { //where initialization occurs: //Register for mouse events on blankArea and the panel. blankArea.addMouseListener(this); addMouseListener(this); ...

public void mousePressed(MouseEvent e) { saySomething("Mouse pressed; # of clicks: " + e.getClickCount(), e); }

public void mouseReleased(MouseEvent e) { saySomething("Mouse released; # of clicks: " + e.getClickCount(), e); }

public void mouseEntered(MouseEvent e) { saySomething("Mouse entered", e); }

public void mouseExited(MouseEvent e) { saySomething("Mouse exited", e); }

public void mouseClicked(MouseEvent e) { saySomething("Mouse clicked (# of clicks: " + e.getClickCount() + ")", e); }

void saySomething(String eventDescription, MouseEvent e) { textArea.append(eventDescription + " detected on " + e.getComponent().getClass().getName() + "." + newline); }}

24 | P a g e

Page 25: Lập trình giao diện Swing trong java

6.KeyEvent – KeyListener

Sự kiện này cho thấy khi người dùng gõ vào bàn phím. Cụ thể, sự kiện này được bắn bởi các thành phần với trọng tâm là bàn phím khi người dùng nhấn phím bàn phím.Sẽ phát sinh ra hàm Keylistener của máy tính để bắt sự kiện này.Ví dụ:

public class KeyEventDemo ... implements KeyListener ... { ...//where initialization occurs: typingArea = new JTextField(20); typingArea.addKeyListener(this);

//Uncomment this if you wish to turn off focus //traversal. The focus subsystem consumes //focus traversal keys, such as Tab and Shift Tab. //If you uncomment the following line of code, this //disables focus traversal and the Tab events //become available to the key event listener. //typingArea.setFocusTraversalKeysEnabled(false); ... /** Handle the key typed event from the text field. */ public void keyTyped(KeyEvent e) { displayInfo(e, "KEY TYPED: "); }

/** Handle the key-pressed event from the text field. */ public void keyPressed(KeyEvent e) { displayInfo(e, "KEY PRESSED: "); }

/** Handle the key-released event from the text field. */ public void keyReleased(KeyEvent e) { displayInfo(e, "KEY RELEASED: "); } ... private void displayInfo(KeyEvent e, String keyStatus){ //You should only rely on the key char if the event //is a key typed event. int id = e.getID(); String keyString; if (id == KeyEvent.KEY_TYPED) { char c = e.getKeyChar(); keyString = "key character = '" + c + "'"; } else { int keyCode = e.getKeyCode(); keyString = "key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode)

25 | P a g e

Page 26: Lập trình giao diện Swing trong java

+ ")"; } int modifiersEx = e.getModifiersEx(); String modString = "extended modifiers = " + modifiersEx; String tmpString = KeyEvent.getModifiersExText(modifiersEx); if (tmpString.length() > 0) { modString += " (" + tmpString + ")"; } else { modString += " (no extended modifiers)"; } String actionString = "action key? "; if (e.isActionKey()) { actionString += "YES"; } else { actionString += "NO"; } String locationString = "key location: "; int location = e.getKeyLocation(); if (location == KeyEvent.KEY_LOCATION_STANDARD) { locationString += "standard"; } else if (location == KeyEvent.KEY_LOCATION_LEFT) { locationString += "left"; } else if (location == KeyEvent.KEY_LOCATION_RIGHT) { locationString += "right"; } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) { locationString += "numpad"; } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN) locationString += "unknown"; } ...//Display information about the KeyEvent... }}

Qua các Demo phần trước chúng ta đã biết gần như hết các sự kiện của java swing,vậy bây giờ chúng ta hãy đến với một ví dụ cụ thể và sinh động của xử lý sự kiện trong java.Swing.

Demo Giải phương trình bậc hai:

Class1:

public class PTB2Engine {

private int a;

26 | P a g e

Page 27: Lập trình giao diện Swing trong java

private int b;

private int c;

public PTB2Engine(int a, int b, int c) {

this.a = a;

this.b = b;

this.c = c;

}

public String compute() {

String kq = "";

if (this.a == 0) {

if (this.b == 0) {

if (this.c == 0) {

kq = "vo so nghien";

} else {

kq = "vo nghiem";

}

} else {

kq = "Pt co 1 no x1=" + (-this.c / this.b);

}

} else {

double delta = this.b * this.b - 4 * this.a * this.c;

if (delta < 0) {

kq = "Vô nghiệm";

} else if (delta == 0) {

kq = "No kép x1=x2=" + (-this.b / (2 * this.a));

} else {

kq = "x1 = " + ((-this.b - Math.sqrt(delta)) / (2 * this.a));

kq += " x2 = " + ((-this.b + Math.sqrt(delta)) / (2 * this.a));

}

}

return kq;

}

}

27 | P a g e

Page 28: Lập trình giao diện Swing trong java

Class2:

btnThoat.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent arg0) {

int ret = JOptionPane.showConfirmDialog(null, "Muốn thoát?", "Thoát", JOptionPane.YES_NO_OPTION);

if (ret == JOptionPane.YES_OPTION) {

System.exit(0);

}

}

});

btnXoa.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent arg0) {

txtb.setText("");

txtc.setText("");

txtkq.setText("");

txta.requestFocus();

}

});

btnGiai.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent arg0) {

String sa = txta.getText();

int a = 0, b = 0, c = 0;

try {

a = Integer.parseInt(sa);

} catch (Exception ex) {

JOptionPane.showMessageDialog(null, "Nhập sai định dạng!");

txta.selectAll();

txta.requestFocus();

return;

}

String sb = txtb.getText();

try {

b = Integer.parseInt(sb);

28 | P a g e

Page 29: Lập trình giao diện Swing trong java

} catch (Exception ex) {

JOptionPane.showMessageDialog(null, "Nhập sai định dạng!")

txtb.selectAll();

txtb.requestFocus();

return;

}

Kết quả như sau:

29 | P a g e