Page 718 - Introduction to Programming with Java: A Problem Solving Approach
P. 718

                684 Chapter 16 GUI Programming Basics
 /***************************************************************
*
SmileyPanel.java
Dean & Dean
This class contains a smiley image and listeners
that enable image dragging and image swapping.
***************************************************************/
*
*
*
*
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SmileyPanel extends JPanel
{
private final ImageIcon SMILEY = new ImageIcon("smiley.gif");
private final ImageIcon SCARED = new ImageIcon("scared.gif");
private final int WIDTH = SMILEY.getIconWidth();
private final int HEIGHT = SMILEY.getIconHeight();
private Point imageCorner; // image's top-left corner location
private Point prevPt;
private ImageIcon image;
// mouse location for previous event
// toggles between smiley and scared
//****************A**p**a**g**o****P**D*F****E**n**h**a**n**c**e**r*********** public SmileyPanel()
{
    }
image = SMILEY;
imageCorner = new Point(0, 0); // image starts at top left
ClickListener clickListener = new ClickListener();
DragListener dragListener = new DragListener();
this.addMouseListener(clickListener); ⎫ ⎬
this.addMouseMotionListener(dragListener);⎭ // end SmileyComponent constructor
//************************************************************
private class ClickListener extends MouseAdapter
{
// When mouse pressed, change to scared image.
public void mousePressed(MouseEvent e)
{
image = SCARED;
prevPt = e.getPoint(); // save current position
repaint();
} // end mousePressed
Add mouse listeners to the JPanel container.
 Figure 16.17a The DragSmiley program’s SmileyPanel class—part A




















































   716   717   718   719   720