LAB 5(4 tiết): Sử dụng sự kiện chuột và bàn phím

Similar documents
LAB 4(4 tiết): Thực hành ứng dụng GUI(tiếp)

LAB 6(4 tiết): Áp dụng các sự kiện chuột, bàn phím và các hàm vẽ

Khối: Cao Đẳng nghề và Trung Cấp Năm 2009

BÀI TẬP THỰC HÀNH LẬP TRÌNH WINDOWS C#

CẤU TRÚC DỮ LIỆU NÂNG CAO

Cài đặt và cấu hình StarWind iscsi trên Windows. iscsi SAN là gì?

Cụ thể những công việc mà AndroidManifest.xml thực hiện: - Đặt tên cho Java package của ứng dụng.

Phần 1: Hướng dẫn sử dụng PictureBox tạo Slide Show

Khoa KH & KTMT Bộ môn Kỹ Thuật Máy Tính

SIEMENS INDUSTRIAL NETWORKS

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

Bộ môn HTMT&TT, Khoa Công Nghệ Thông Tin và TT, ĐH Cần Thơ

Hướng dẫn cài đặt FPT

TÀI LIỆU THỰC HÀNH MÔN CƠ SỞ DỮ LIỆU NÂNG CAO

Entity Framework (EF)

B6: Time to coding. Đi tới src\at.exam tạo một class mới là CustomViewGroup với nội dung sau: Mã: package at.exam;

HƯỚNG DẪN SỬ DỤNG HỆ THỐNG CẬP NHẬT CHỨNG THƯ SỐ HOTLINE:

User interfaces and Swing

Tạo Project với MPLAB

Giáo trình này được biên dịch theo sách hướng dẫn của Sun Light. Vì là hướng dẫn kỹ thuật, trong này những thuật ngữ kỹ thuật bằng tiếng Anh tôi chỉ

HTML DOM - Forms. MSc. nguyenhominhduc

LẬP TRÌNH WINDOWS FORM VỚI CÁC CONTROL NÂNG CAO (Các control trình bày dữ liệu dưới dạng danh sách)

Tài liệu hướng dẫn: Stored Procedure

Internet Protocol. Bởi: Phạm Nguyễn Bảo Nguyên

HƯỚNG DẪN SỬ DỤNG PLESK PANEL

HƯỚNG DẪN SỬ DỤNG ĐẦU GHI H.264 DVR VISION VS (4CH - 8CH - 16CH)

HƢỚNG DẪN TRIỂN KHAI KASPERSKY - MOBILE DEVICE MANAGEMENT

STACK và QUEUE. Lấy STACK

I. Hướng Dẫn Đăng Nhập:

Lab01: M V C Lưu ý: Để thực hành, các bạn phải cài Visual Studio 2013 trở lên mới hỗ trợ MVC5.

LÂ P TRI NH WEB ASP.NET

Đa ngôn ngữ (Internationalization) trong Servlet

BELGIUM ONLINE APPOINTMENT

HƯỚNG DẪN CÀI ĐẶT PHẦN MỀM DIỆT VIRUS AVIRA

GV: Phạm Đình Sắc or

Exceptions. Outline 7/31/2012. Exceptions. Exception handling is an important aspect of objectoriented. Chapter 10 focuses on:

BÀI 1: VBA LÀ GÌ? TẠO MACRO, ỨNG DỤNG CÁC HÀM TỰ TẠO (UDF), CÀI ĐẶT ADD-INS VBA là gì?

Online Appointment System will work better with below conditions/ Hệ thống đặt hẹn online sẽ hoạt động tốt hơn với điều kiện sau đây:

Tröôøng Ñaïi Hoïc Baùch Khoa Tp.HCM LẬP TRÌNH MINICHAT. Bài giảng 3. Trang1. Khoa Khoa Học Và Kỹ Thuật Máy Tính

HƯỚNG DẪN SỬ DỤNG NHANH MINDJET MIND MANAGER

SIMULATE AND CONTROL ROBOT

GIẢI THUẬT ĐỊNH TUYẾN (ROUTING ALGORITHM)

ĐỌC, GHI XML VỚI C# TRONG ADO.NET --- SỬ DỤNG VISUAL STUDIO

Nhấn nút New để tạo 1 biến mới Trang 17

B3: Bên khung Package Explore bên trái đi tới thư mục res, bạn sẽ thấy có 3 thư mục con:

Nội dung chính của chương. Các công nghệ đĩa cứng Cấu tạo vật lý của đĩa cứng Cấu tạo logic của đĩa cứng Cài đặt đĩa cứng như thế nào?

Phần 2. SỬ DỤNG POWERPOINT ĐỂ CHUẨN BỊ NỘI DUNG TRÌNH BÀY

Chương 6. Transport Layer. Tài liệu : Forouzan, Data Communication and Networking

B5: Time to coding. Tới thư mục src/example.java và thay đổi nội dung file như sau: Mã: package at.exam;

CHƯƠNG 2: CÁC ĐẶC ĐIỂM VỀ MÔI TRƯỜNG PHÁT TRIỂN (IDE)

ĐỀ CƯƠNG CHI TIẾT HỌC PHẦN

BÀI 6 LÀM VIỆC VỚI THÀNH PHẦN MỞ RỘNG CỦA CSS3

Bài Thực hành Asp.Net - Buổi 1 - Trang: 1

Graphical User Interfaces 2

BẢO MẬT TRONG SQL SERVER

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

2IS45 Programming

Kỹ thuật thu nhỏ đối tượng trong Design (Layout)

Tình huống 1: PPPoE với Username và Password

Bộ môn MMT&TT, Khoa Công Nghệ Thông Tin và TT, ĐH Cần Thơ

Chương 7. Application Layer. Tài liệu : Forouzan, Data Communication and Networking

Chương 5. Network Layer. Phần 1 - Địa chỉ IPv4. Tài liệu : Forouzan, Data Communication and Networking

Bài tập lớn số 1. Giả lập bộ định thời

NHÚNG. Vi ñiều khiển BM Kỹ Thuật ðiện Tử - ðh Bách Khoa TP.HCM 2

G51PRG: Introduction to Programming Second semester Applets and graphics

Bài 10: Cấu trúc dữ liệu

Chủ đề 7: Triển khai và Bảo trì. COMP1026 Introduction to Software Engneering CH7-1 HIENLTH

Chương 5. Network Layer 19/09/2016 1

Mô hình dữ liệu quan hệ (Relational data model)

BÀI GIẢNG CHƯƠNG 3 GIAO TIẾP KẾT NỐI SỐ LIỆU

TÀI LIỆU HƯỚNG DẪN SỬ DỤNG HOSTING PLESK PANEL

HƯỚNG DẪN CÁCH SỬ DỤNG WINDOWS MOVIE MAKER

Bài tập căn bản Visual Basic.Net Vòng lặp. txtn. txtketqua. btntinh. txtn. txtketqua. btntinh. Trang 1

Cập nhật ResultSet trong JDBC

LAB IP SLA Bài 1. Bùi Quốc Kỳ ***

TỔNG QUAN VỀ.NET VÀ C#

Câu 1: (2 điểm) So sách giữa 2 đối tượng Response và Request. Cho ví dụ minh hoạ.

Khoa Công Nghệ Thông Tin Trường Đại Học Cần Thơ. Những hỗ trợ tiên tiến khác của SQL. Đỗ Thanh Nghị

Virtual LAB Summary (CCNA Routing & Switching)

Chapter 4 Menus, Functions And Common Dialog

Programmierpraktikum

MỤC LỤC. Giáo trình Thiết kế web Trang 1

Time Picker trong Android

- Chạy file cài đặt: kerio-kwf-whql win32.exe. Hộp thoại Choose Setup Language chọn English (United States), chọn

Khối: Cao Đẳng nghề và Trung Cấp Năm 2009

Tính kế thừa-2. Bởi: Thanh Hiền Vũ. Định nghĩa lại các thành viên lớp cơ sở trong một lớp dẫn xuất:

HỢP ĐỒNG MUA BÁN HÀNG HÓA QUỐC TẾ GV: NGUYỄN THỊ BÍCH PHƯỢNG

PHÁT TRIỂN ỨNG DỤNG WEB

HƯỚNG DẪN SỬ DỤNG DỊCH VỤ CDN

NHẬP MÔN LẬP TRÌNH KHOA HỌC DỮ LIỆU. Bài 10: Thư viện Pandas (2)

LEECH Chưởng trình Chat bằng c# : Source :

Programming Languages and Techniques (CIS120)

Tìm hiểu Group Policy Object và các ví dụ

Exam: Applet, Graphics, Events: Mouse, Key, and Focus

PHÁT TRIỂN ỨNG DỤNG DI ĐỘNG NÂNG CAO

1 Bước 1: Test thử kit LaunchPad.

Lập trình chuyên nâng cao. Lập trình phân tán (Distributed computing

Giao tiếp giữa các tiến trình

LINQ TO SQL & ASP.NET

Mô hình thực thi ASP.NET page Xây dựng Web Form HTML Control và Web Control Bổ sung code vào Page Page Event Life Cycle Postback event

Transcription:

THỰC HÀNH CÔNG CỤ VÀ MÔI TRƯỜNG VÀ LẬP TRÌNH 2 --------------------------------------------------------------------------------------------------- TS. Võ Phương Bình Email: binhvp@dlu.edu.vn Information Technology Faculty - Dalat University Website: http://it.dlu.edu.vn/ivp-lab --------------------------------------------------------------------------------------------------- LAB 5(4 tiết): Sử dụng sự kiện chuột và bàn phím A. Mục tiêu: - Hiểu biết và sử dụng được các sự kiện chuột và bàn phím - Xử lý các sự kiện trên môi trường GUI B. Kết quả sau khi hoàn thành: - Sử dụng được các thành phần thiết kế để có thể tạo ra các giao diện. - Xây dựng các ứng dụng có sự kiện chuột và bàn phím. - Nhúng vào website tự thiết kế đơn giản. C. Luyện tập: Quy tắc sử dụng sự kiện: Khai báo kế thừa interface phù hợp với sự kiện cần xử lý. Phải định nghĩa lại tất cả các phương thức của interface được kế thừa. Ví dụ: 1. Cần xử lý các sự kiện ActionEvent như click trên Button, Menu thì kế thừa interface ActionListener. Ta phải khai báo phương thức actionperformed(actionevent e). 2. Cần xử lý về sự kiện chuột thì kế thừa interface MouseListener. Ta phải định nghĩa các phương thức sau: public void mousepressed(mouseevent evt); public void mousereleased(mouseevent evt); public void mouseclicked(mouseevent evt); public void mouseentered(mouseevent evt); public void mouseexited(mouseevent evt); D. Bài tập. Bài 1: Hãy viết chương trình xử lý sự kiện choṇ ma u va nhâ p pha i chuột ve hi nh chư nhâ t như minh họa sau:

Hươ ng dâñ: import java.awt.*; import java.awt.event.*; import javax.swing.*; class RainbowPalette extends JPanel implements MouseListener { /* The currently selected color is stored in the variable selectedcolor. The hue of this color -- a float value in the range 0.0F to 1.0F is stored in selectedhue. The value of selectedhue is used to determine where to draw the hilite on the palette */ private float selectedhue = 0; private Color selectedcolor = Color.getHSBColor(0,1,1);

RainbowPalette() { // Constructor. Set the component to listen for mouse clicks // on itself, and set the preferred size. The gray background // color will show around the edges of the colored palette. addmouselistener(this); setpreferredsize( new Dimension(256, 24) ); setbackground(color.gray); public Color getselectedcolor() { // Return the color that is currently selected in the palette. return selectedcolor; public void paintcomponent(graphics g) { // Draw the palette, and add a white rectangle to hilite // the selected color. super.paintcomponent(g); int width = getwidth(); int height = getheight(); for (int i = 0; i < width - 8; i++) { float hue = (float)i / (width-8); g.setcolor( Color.getHSBColor(hue, 1, 1) );

g.drawline(i+4,4,i+4,height-5); int x = 4 + (int)(selectedhue*(width-8)); // x-coord of selected color. g.setcolor(color.white); g.drawrect(x-2,3,2,height-7); // Draw the hilite. g.drawrect(x-3,2,4,height-5); public void mousepressed(mouseevent evt) { // When the user clicks on the component, select the // color that the user clicked. But make sure that // the selectedhue is in the legal range, 0 to 1. int x = evt.getx(); selectedhue = (float)x / (getsize().width - 4); if (selectedhue < 0) selectedhue = 0; else if (selectedhue > 1) selectedhue = 1; selectedcolor = Color.getHSBColor(selectedHue, 1, 1); repaint(); public void mousereleased(mouseevent evt) {

public void mouseclicked(mouseevent evt) { public void mouseentered(mouseevent evt) { public void mouseexited(mouseevent evt) { // end class RainbowPalette import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.arraylist; public class SimpleDrawRects extends JFrame { RainbowPalette colorinput; // A palette of colors that appears // at the bottom of the applet. The // RainbowPalette class is non-standard, // and is defined externally to this file. public SimpleDrawRects() { // Set up the applet with a drawing surface and palette. setbackground(color.black); // shows along border

Rects canvas = new Rects(); colorinput = new RainbowPalette(); getcontentpane().add(canvas, BorderLayout.CENTER); getcontentpane().add(colorinput, BorderLayout.SOUTH); public Insets getinsets() { // Leave space for a black border around the applet. return new Insets(2,2,2,2); //-------------------------- Nested classes ------------------- static class ColoredRect { // Represents the data for one colored rectangle. int x, y, width, height; // Location and size of rect. Color color; // Color of rect. class Rects extends JPanel implements MouseListener, MouseMotionListener {

// This class is a canvas that shows some colored rectangles. // The user adds a rectangle by right-clicking on the canvas. // The user can delete a rectangle by Alt-clicking it, and can // move it out in front of the other rectangles by Shift-clicking // it. The user can also click-and-drag rectangles to move them // around the canvas. private ArrayList rects; // The colored rectangles are represented by objects // of type ColoredRect that are stored in this ArrayList. /* Variables for implementing dragging. */ private boolean dragging; // This is true when dragging is in progress. private ColoredRect dragrect; // The rect that is being dragged (if dragging is true). private int offsetx, offsety; // The distance from the upper left corner of the // dragrect to the point where the user clicked // the rect. This offset is maintained as the // rect is dragged. Rects() {

// Constructor. The canvas listens for mouse events, and an // ArrayList is created to hold the ColoredRects. setbackground(color.white); addmouselistener(this); addmousemotionlistener(this); rects = new ArrayList(); ColoredRect findrect(int x, int y) { // Find the topmost rect that contains the point (x,y). // Return null if no rect contains that point. // The rects in the ArrayList are considered in reverse order // so that if one lies on top of another, the one on top // is seen first and is returned. for (int i = rects.size() - 1; i >= 0; i--) { ColoredRect rect = (ColoredRect)rects.get(i); if ( x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height ) return rect; // (x,y) is inside this rect. return null;

void bringtofront(coloredrect rect) { // If rect!= null, move it out in front of the other // rects by moving it to the last position in the ArrayList. if (rect!= null) { rects.remove(rect); // Remove rect from current position. rects.add(rect); // Put rect in the ArrayList in last position. repaint(); void deleterect(coloredrect rect) { // If rect!= null, remove it from the ArrayList and from the screen. if (rect!= null) { rects.remove(rect); repaint(); public void paintcomponent(graphics g) { // Draw all the rects in the ArrayList. super.paintcomponent(g); // Fills with background color, white. for (int i = 0; i < rects.size(); i++) { ColoredRect rect = (ColoredRect)rects.get(i);

g.setcolor(rect.color); g.fillrect(rect.x, rect.y, rect.width, rect.height); g.setcolor(color.black); g.drawrect(rect.x, rect.y, rect.width - 1, rect.height - 1); public void mousepressed(mouseevent evt) { // The user clicked on the canvas. This can have several effects... if (dragging) // If dragging is already in progress, just return. return; if (evt.ismetadown()) { // User right-clicked or command clicked. Make a new // rectangle and add it to the canvas. Every rectangle is // 60 pixels wide and 30 pixels tall. The point where the // user clicked is at the center of the rectangle. It's // color is the selected color in the colorinput palette. ColoredRect rect = new ColoredRect(); rect.x = evt.getx() - 30; rect.y = evt.gety() - 15; rect.width = 60;

rect.height = 30; rect.color = colorinput.getselectedcolor(); rects.add(rect); repaint(); else if (evt.isshiftdown()) { // User shift-clicked. More the rect that the user // clicked (if any) to the front. Note that findrect() // might return null, but bringtofront() accounts for that. bringtofront( findrect( evt.getx(), evt.gety() ) ); else if (evt.isaltdown()) { // User alt-clicked or middle-clicked. Delete the rect // that the user clicked. deleterect( findrect( evt.getx(), evt.gety() ) ); else { // This is a simple left-click. Start dragging the // rect that the user clicked (if any). dragrect = findrect( evt.getx(), evt.gety() ); if (dragrect!= null) { dragging = true; // Begin a drag operation. offsetx = evt.getx() - dragrect.x;

offsety = evt.gety() - dragrect.y; // end mousepressed() public void mousereleased(mouseevent evt) { // End the drag operation, if one is in progress. if (dragging == false) return; dragrect = null; dragging = false; public void mousedragged(mouseevent evt) { // Continue the drag operation if one is in progress. // Move the rect that is being dragged to the current // mouse position. But clamp it so that it can't // be more than halfway off the screen. if (dragging == false) return;

dragrect.x = evt.getx() - offsetx; // Get new postion of rect. dragrect.y = evt.gety() - offsety; /* Clamp (x,y) to a permitted range, as described above. */ if (dragrect.x < - dragrect.width / 2) dragrect.x = - dragrect.width / 2; else if (dragrect.x + dragrect.width/2 > getsize().width) dragrect.x = getsize().width - dragrect.width / 2; if (dragrect.y < - dragrect.height / 2) dragrect.y = - dragrect.height / 2; else if (dragrect.y + dragrect.height/2 > getsize().height) dragrect.y = getsize().height - dragrect.height / 2; /* Redraw the canvas, with the rect in its new position. */ repaint(); // end mousedragged() public void mouseclicked(mouseevent evt) { public void mouseentered(mouseevent evt) {

public void mouseexited(mouseevent evt) { public void mousemoved(mouseevent evt) { // end nested class Rects // end class SimpleDrawRects Bài 2: Viết chương trình paint đơn giản, cho phép dùng chuột vẽ như minh họa sau: Minh họa: Hươ ng dâñ: /* A simple program where the user can sketch curves in a variety of colors. A color palette is shown on the right of the applet.

The user can select a drawing color by clicking on a color in the palette. Under the colors is a "Clear button" that the user can press to clear the sketch. The user draws by clicking and dragging in a large white area that occupies most of the applet. The user's drawing is not persistant. It is cleared if the applet is resized. If it is covered, in whole or part, and then uncovered, the part was covered is gone. */ import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.jframe; public class SimplePaint extends JFrame implements MouseListener, MouseMotionListener { private final static int BLACK = 0, RED = 1, GREEN = 2, BLUE = 3, // Some constants to make // the code more readable. // These numbers code for

CYAN = 4, // the differnet drawing colors. MAGENTA = 5, YELLOW = 6; private int currentcolor = BLACK; // The currently selected drawing color, // coded as one of the above constants. /* The following variables are used when the user is sketching a curve while dragging a mouse. */ private int prevx, prevy; // The previous location of the mouse. private boolean dragging; // This is set to true while the user is drawing. private Graphics graphicsfordrawing; // A graphics context for the applet // that is used to draw the user's curve. public SimplePaint() { // When the applet is first created, the applet is set to // listen for mouse events and mouse motion events from // itself.

addmouselistener(this); addmousemotionlistener(this); public void update(graphics g) { // Redefine update so it does not fill the applet with the // background color before calling paint(). This is OK // since the paint() method always draws over the entire // surface of the applet. paint(g); public void paint(graphics g) { // Draw the contents of the applet. Since no information is // saved about what the user has drawn, the user's drawing // is erased whenever this routine is called. int width = getsize().width; // Width of the applet. int height = getsize().height; // Height of the applet. int colorspacing = (height - 56) / 7;

// Distance between the top of one colored rectangle in the palette // and the top of the rectangle below it. The height of the // rectangle will be colorspacing - 3. There are 7 colored rectangles, // so the available space is divided by 7. The available space allows // for the gray border and the 50-by-50 CLEAR button. /* First, fill in the white drawing area, allowing for a three-pixel border at top, bottom, and left and allowing for the 56-pixel wide strip on the right that is occupied by the color palette and CLEAR button. (I could just fill the whole applet with white and then draw over some of it, but that leads to increased flickering when the applet is redrawn.) */ g.setcolor(color.white); g.fillrect(3, 3, width - 59, height - 6); /* Draw a 3-pixel border around the applet in gray. This has to be done by drawing three rectangles of different sizes. */ g.setcolor(color.gray); g.drawrect(0, 0, width-1, height-1); g.drawrect(1, 1, width-3, height-3);

g.drawrect(2, 2, width-5, height-5); /* Draw a 56-pixel wide gray rectangle along the right edge of the applet. The color palette and Clear button will be drawn on top of this. (This covers some of the same area as the border I just drew. */ g.fillrect(width - 56, 0, 56, height); /* Draw the "Clear button" as a 50-by-50 white rectangle in the lower right corner of the applet, allowing for a 3-pixel border. */ g.setcolor(color.white); g.fillrect(width-53, height-53, 50, 50); g.setcolor(color.black); g.drawrect(width-53, height-53, 49, 49); g.drawstring("clear", width-48, height-23); /* Draw the seven color rectangles. */ g.setcolor(color.black); g.fillrect(width-53, 3 + 0*colorSpacing, 50, colorspacing-3); g.setcolor(color.red); g.fillrect(width-53, 3 + 1*colorSpacing, 50, colorspacing-3);

g.setcolor(color.green); g.fillrect(width-53, 3 + 2*colorSpacing, 50, colorspacing-3); g.setcolor(color.blue); g.fillrect(width-53, 3 + 3*colorSpacing, 50, colorspacing-3); g.setcolor(color.cyan); g.fillrect(width-53, 3 + 4*colorSpacing, 50, colorspacing-3); g.setcolor(color.magenta); g.fillrect(width-53, 3 + 5*colorSpacing, 50, colorspacing-3); g.setcolor(color.yellow); g.fillrect(width-53, 3 + 6*colorSpacing, 50, colorspacing-3); /* Draw a 2-pixel white border around the color rectangle of the current drawing color. */ g.setcolor(color.white); g.drawrect(width-55, 1 + currentcolor*colorspacing, 53, colorspacing); g.drawrect(width-54, 2 + currentcolor*colorspacing, 51, colorspacing-2); // end paint() private void changecolor(int y) {

// Change the drawing color after the user has clicked the // mouse on the color palette at a point with y-coordinate y. // (Note that I can't just call repaint and redraw the whole // applet, since that whould erase the user's drawing.) int width = getsize().width; int height = getsize().height; // Width of applet. // Height of applet. int colorspacing = (height - 56) / 7; // Space for one color rectangle. int newcolor = y / colorspacing; // Which color number was clicked? if (newcolor < 0 newcolor > 6) // Make sure the color number is valid. return; /* Remove the hilite from the current color, by drawing over it in gray. Then change the current drawing color and draw a hilite around the new drawing color. */ Graphics g = getgraphics(); g.setcolor(color.gray); g.drawrect(width-55, 1 + currentcolor*colorspacing, 53, colorspacing); g.drawrect(width-54, 2 + currentcolor*colorspacing, 51, colorspacing-2); currentcolor = newcolor; g.setcolor(color.white);

g.drawrect(width-55, 1 + currentcolor*colorspacing, 53, colorspacing); g.drawrect(width-54, 2 + currentcolor*colorspacing, 51, colorspacing-2); g.dispose(); // end changecolor() private void setupdrawinggraphics() { // This routine is called in mousepressed when the // user clicks on the drawing area. It sets up the // graphics context, graphicsfordrawing, to be used // to draw the user's sketch in the current color. graphicsfordrawing = getgraphics(); switch (currentcolor) { case BLACK: graphicsfordrawing.setcolor(color.black); break; case RED: graphicsfordrawing.setcolor(color.red); break; case GREEN: graphicsfordrawing.setcolor(color.green); break;

case BLUE: graphicsfordrawing.setcolor(color.blue); break; case CYAN: graphicsfordrawing.setcolor(color.cyan); break; case MAGENTA: graphicsfordrawing.setcolor(color.magenta); break; case YELLOW: graphicsfordrawing.setcolor(color.yellow); break; // end setupdrawinggraphics() public void mousepressed(mouseevent evt) { // This is called when the user presses the mouse anywhere // in the applet. There are three possible responses, // depending on where the user clicked: Change the // current color, clear the drawing, or start drawing // a curve. (Or do nothing if user clicks on the border.)

int x = evt.getx(); // x-coordinate where the user clicked. int y = evt.gety(); // y-coordinate where the user clicked. int width = getsize().width; // Width of the applet. int height = getsize().height; // Height of the applet. if (dragging == true) // Ignore mouse presses that occur return; // when user is already drawing a curve. // (This can happen if the user presses // two mouse buttons at the same time.) if (x > width - 53) { // User clicked to the right of the drawing area. // This click is either on the clear button or // on the color palette. if (y > height - 53) repaint(); // Clicked on "CLEAR button". else changecolor(y); // Clicked on the color palette. else if (x > 3 && x < width - 56 && y > 3 && y < height - 3) { // The user has clicked on the white drawing area. // Start drawing a curve from the point (x,y).

prevx = x; prevy = y; dragging = true; setupdrawinggraphics(); // end mousepressed() public void mousereleased(mouseevent evt) { // Called whenever the user releases the mouse button. // If the user was drawing a curve, the curve is done, // so we should set drawing to false and get rid of // the graphics context that we created to use during // the drawing. if (dragging == false) return; // Nothing to do because the user isn't drawing. dragging = false; graphicsfordrawing.dispose(); graphicsfordrawing = null;

public void mousedragged(mouseevent evt) { // Called whenever the user moves the mouse // while a mouse button is held down. If the // user is drawing, draw a line segment from the // previous mouse location to the current mouse // location, and set up prevx and prevy for the // next call. Note that in case the user drags // ouside of the drawing area, the values of // x and y are "clamped" to lie within this // area. This avoids drawing on the color palette // or clear buton. if (dragging == false) return; // Nothing to do because the user isn't drawing. int x = evt.getx(); // x-coordinate of mouse. int y = evt.gety(); // y=coordinate of mouse. if (x < 3) // Adjust the value of x, x = 3; // to make sure it's in if (x > getsize().width - 57) // the drawing area. x = getsize().width - 57;

if (y < 3) // Adjust the value of y, y = 3; // to make sure it's in if (y > getsize().height - 4) // the drawing area. y = getsize().height - 4; graphicsfordrawing.drawline(prevx, prevy, x, y); // Draw the line. prevx = x; // Get ready for the next line segment in the curve. prevy = y; // end mousedragged. public void mouseentered(mouseevent evt) { // Some empty routines. public void mouseexited(mouseevent evt) { // (Required by the MouseListener public void mouseclicked(mouseevent evt) { // and MouseMotionListener public void mousemoved(mouseevent evt) { // interfaces). // end class SimplePaint Bài 3: Viết chương trình xử lý sự kiện bàn phím như minh họa sau: sư duṇg ba n phi m điê u hươ ng (muḭ tên left, right, up, down) đê di chuyê n hi nh vuông ma u đo.

Hươ ng dâñ: /* */ A colored square is drawn on the JFrame. By pressing the arrow keys, the user can move the square up, down, left, or right. By pressing the keys R, G, B, or K, the user can change the color of the square to red, green, blue, or black, respectively. Of course, none of the keys will have any effect if the applet does not have the keyboard input focus. The applet changes appearance when it has the input focus. A cyan-colored border is drawn around it. When it does not have the input focus, the message "Click to activate" is displayed and the border is gray. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class KeyboardAndFocusDemo extends JFrame implements KeyListener, FocusListener, MouseListener { // (Note: MouseListener is implemented only so that // the applet can request the input focus when // the user clicks on it.) static final int SQUARE_SIZE = 40; // Length of a side of the square. Color squarecolor; // The color of the square. int squaretop, squareleft; // Coordinates of top-left corner of square. boolean focussed = false; // True when this applet has input focus. DisplayPanel canvas; // The drawing surface on which the applet draws, // belonging to a nested class DisplayPanel, which

// is defined below. public KeyboardAndFocusDemo () { // Initialize the applet; set it up to receive keyboard // and focus events. Place the square in the middle of // the applet, and make the initial color of the square red. // Then, set up the drawing surface. squaretop = getsize().height / 2 - SQUARE_SIZE / 2; squareleft = getsize().width / 2 - SQUARE_SIZE / 2; squarecolor = Color.red; pane. canvas = new DisplayPanel(); // Create drawing surface and setcontentpane(canvas); // install it as the applet's content canvas.setbackground(color.white); // Set the background color of the canvas. canvas.addfocuslistener(this); // Set up the applet to listen for events canvas.addkeylistener(this); // from the canvas. canvas.addmouselistener(this); // end init(); class DisplayPanel extends JPanel { // An object belonging to this nested class is used as // the content pane of the applet. It displays the // moving square on a white background with a border // that changes color depending on whether this // component has the input focus or not. public void paintcomponent(graphics g) { super.paintcomponent(g); // Fills the panel with its // background color, which is white. /* Draw a 3-pixel border, colored cyan if the applet has the keyboard focus, or in light gray if it does not. */ if (focussed) g.setcolor(color.cyan); else g.setcolor(color.lightgray); int width = getsize().width; // Width of the applet. int height = getsize().height; // Height of the applet. g.drawrect(0,0,width-1,height-1); g.drawrect(1,1,width-3,height-3); g.drawrect(2,2,width-5,height-5); /* Draw the square. */ g.setcolor(squarecolor); g.fillrect(squareleft, squaretop, SQUARE_SIZE, SQUARE_SIZE);

/* If the applet does not have input focus, print a message. */ if (!focussed) { g.setcolor(color.magenta); g.drawstring("click to activate",7,20); // end paintcomponent() // end nested class DisplayPanel // ------------------- Event handling methods ---------------------- public void focusgained(focusevent evt) { // The applet now has the input focus. focussed = true; canvas.repaint(); // redraw with cyan border public void focuslost(focusevent evt) { // The applet has now lost the input focus. focussed = false; canvas.repaint(); // redraw without cyan border public void keytyped(keyevent evt) { // The user has typed a character, while the // applet has the input focus. If it is one // of the keys that represents a color, change // the color of the square and redraw the applet. char ch = evt.getkeychar(); // The character typed. if (ch == 'B' ch == 'b') { squarecolor = Color.blue; canvas.repaint(); else if (ch == 'G' ch == 'g') { squarecolor = Color.green; canvas.repaint(); else if (ch == 'R' ch == 'r') { squarecolor = Color.red; canvas.repaint(); else if (ch == 'K' ch == 'k') { squarecolor = Color.black; canvas.repaint(); // end keytyped() public void keypressed(keyevent evt) { // Called when the user has pressed a key, which can be

// a special key such as an arrow key. If the key pressed // was one of the arrow keys, move the square (but make sure // that it doesn't move off the edge, allowing for a // 3-pixel border all around the applet). int key = evt.getkeycode(); // keyboard code for the key that was pressed if (key == KeyEvent.VK_LEFT) { squareleft -= 8; if (squareleft < 3) squareleft = 3; canvas.repaint(); else if (key == KeyEvent.VK_RIGHT) { squareleft += 8; if (squareleft > getsize().width - 3 - SQUARE_SIZE) squareleft = getsize().width - 3 - SQUARE_SIZE; canvas.repaint(); else if (key == KeyEvent.VK_UP) { squaretop -= 8; if (squaretop < 3) squaretop = 3; canvas.repaint(); else if (key == KeyEvent.VK_DOWN) { squaretop += 8; if (squaretop > getsize().height - 3 - SQUARE_SIZE) squaretop = getsize().height - 3 - SQUARE_SIZE; canvas.repaint(); // end keypressed() public void keyreleased(keyevent evt) { // empty method, required by the KeyListener Interface public void mousepressed(mouseevent evt) { // Request that the input focus be given to the // canvas when the user clicks on the applet. canvas.requestfocus(); public void mouseentered(mouseevent evt) { // Required by the public void mouseexited(mouseevent evt) { // MouseListener public void mousereleased(mouseevent evt) { // interface. public void mouseclicked(mouseevent evt) { // end class KeyboardAndFocusDemo

E. Kết quả thực hành. - Sinh viên thực hành ứng dụng trên GUI. - Thời gian thực hành: 4 tiết. F. Đánh giá: - Kiểm tra lại chương trình, thử các kết quả. - Bắt các lỗi bằng cách sử dụng các phần bắt lỗi: try catch. G.Phụ lục(file đi kèm). -------------------Hết-------------------