SourceForge.net Logo
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.awt.image.*;

public class BufferedShapeMover extends Applet{

	static protected Label label;

	public void init(){
		//Initialize the layout.
		setLayout(new BorderLayout());
		add(new BSMCanvas());
		label = new Label("Drag rectangle around within the area");
		add("South", label);
	}

    public static void main(String s[]) {
        Frame f = new Frame("BufferedShapeMover");
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}
        });
	Applet applet = new BufferedShapeMover();
	f.add("Center", applet);
	applet.init();
	f.pack();
        f.setSize(new Dimension(550,250));
        f.show();
    }

}

class BSMCanvas extends Canvas implements MouseListener, MouseMotionListener{

	Rectangle rect = new Rectangle(0, 0, 100, 50);
	BufferedImage bi;
	Graphics2D big;

        // Holds the coordinates of the user's last mousePressed event.
	int last_x, last_y;
	boolean firstTime = true;
	TexturePaint fillPolka, strokePolka;
        Rectangle area;

        // True if the user pressed, dragged or released the mouse outside of the rectangle; false otherwise.
	boolean pressOut = false;		

	public BSMCanvas(){
                setBackground(Color.white);
                addMouseMotionListener(this);
                addMouseListener(this);

		// Creates the fill texture paint pattern.
                bi = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB);
                big = bi.createGraphics();
                big.setColor(Color.pink);
                big.fillRect(0, 0, 7, 7);
                big.setColor(Color.cyan);
                big.fillOval(0, 0, 3, 3);
                Rectangle r = new Rectangle(0,0,5,5);
                fillPolka = new TexturePaint(bi, r);
		big.dispose();

		//Creates the stroke texture paint pattern.
                bi = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB);
		big = bi.createGraphics();		
		big.setColor(Color.cyan);
                big.fillRect(0, 0, 7, 7);
                big.setColor(Color.pink);
                big.fillOval(0, 0, 3, 3);
                r = new Rectangle(0,0,5,5);
                strokePolka = new TexturePaint(bi, r);
		big.dispose();
	}

        // Handles the event of the user pressing down the mouse button.
	public void mousePressed(MouseEvent e){

		last_x = rect.x - e.getX();
		last_y = rect.y - e.getY();

                // Checks whether or not the cursor is inside of the rectangle while the user is pressing themouse.
		if(rect.contains(e.getX(), e.getY())){
			updateLocation(e);
		} else {
		BufferedShapeMover.label.setText("First position the cursor on the rectangle and then drag.");
			pressOut = true;
		}
	}

        // Handles the event of a user dragging the mouse while holding down the mouse button.
	public void mouseDragged(MouseEvent e){

		if(!pressOut){
			 updateLocation(e);
		} else {  
		BufferedShapeMover.label.setText("First position the cursor on the rectangle and then drag.");
		}
	}

        // Handles the event of a user releasing the mouse button.
	public void mouseReleased(MouseEvent e){

                // Checks whether or not the cursor is inside of the rectangle when the user releases the
		// mouse button.   
		if(rect.contains(e.getX(), e.getY())){
			updateLocation(e);
		} else {
		BufferedShapeMover.label.setText("First position the cursor on the rectangle and then drag.");
			pressOut = false;
		}
	}

	// This method required by MouseListener.
	public void mouseMoved(MouseEvent e){}

        // These methods are required by MouseMotionListener.
	public void mouseClicked(MouseEvent e){}
	public void mouseExited(MouseEvent e){}
	public void mouseEntered(MouseEvent e){}
	public void updateLocation(MouseEvent e){

		rect.setLocation(last_x + e.getX(), last_y + e.getY());
                /*
                 * Updates the label to reflect the location of the
                 * current rectangle 
                 * if checkRect returns true; otherwise, returns error message.
                 */
                if (checkRect()) {
                    BufferedShapeMover.label.setText("Rectangle located at " +
                                                     rect.getX() + ", " +
                                                     rect.getY());
                } else {
                    BufferedShapeMover.label.setText("Please don't try to "+
                                                     " drag outside the area.");
                }
		repaint();
	}

	public void paint(Graphics g){
                update(g);
	}

	public void update(Graphics g){
		Graphics2D g2 = (Graphics2D)g;
                 
          	if(firstTime){
                    Dimension dim = getSize();
                    int w = dim.width;
                    int h = dim.height;
                    area = new Rectangle(dim);
		    bi = (BufferedImage)createImage(w, h);
		    big = bi.createGraphics();
		    rect.setLocation(w/2-50, h/2-25);
		    big.setStroke(new BasicStroke(8.0f));
		    firstTime = false;
		} 

		// Clears the rectangle that was previously drawn.
		big.setColor(Color.white);
		big.clearRect(0, 0, area.width, area.height);

		// Draws and fills the newly positioned rectangle to the buffer.
		big.setPaint(strokePolka);
		big.draw(rect);
		big.setPaint(fillPolka);
		big.fill(rect);

		// Draws the buffered image to the screen.
		g2.drawImage(bi, 0, 0, this);
	}
	/*
         * Checks if the rectangle is contained within the applet window.  If the rectangle
         * is not contained withing the applet window, it is redrawn so that it is adjacent
         * to the edge of the window and just inside the window.
	 */
	boolean checkRect(){
            if (area == null) {
                return false;
            }
		if(area.contains(rect.x, rect.y, 100, 50)){
			return true;
		}
		int new_x = rect.x;
		int new_y = rect.y;

		if((rect.x+100)>area.width){
			new_x = area.width-99;
		}
		if(rect.x < 0){  
			new_x = -1;
		}
		if((rect.y+50)>area.height){
			new_y = area.height-49;
		}
		if(rect.y < 0){  
			new_y = -1;
		}
		rect.setLocation(new_x, new_y);
		return false;
	}

}




Tutorials

Linux System Admin Tips: There are over 200 Linux tips and tricks in this article. That is over 100 pages covering everything from NTP, setting up 2 IP address on one NIC, sharing directories among several users, putting running jobs in the background, find out who is doing what on your system by examining open sockets and the ps command, how to watch a file, how to prevent even root from deleting a file, tape commands, setting up cron jobs, using rsync, using screen conveniently with emacs, how to kill every process for a user, security tips and a lot more. These tip grow weekly. The above link will download the text version for easy grep searching. There is also an html version here.

Breaking Firewalls with OpenSSH and PuTTY: If the system administrator deliberately filters out all traffic except port 22 (ssh), to a single server, it is very likely that you can still gain access other computers behind the firewall. This article shows how remote Linux and Windows users can gain access to firewalled samba, mail, and http servers. In essence, it shows how openSSH and Putty can be used as a VPN solution for your home or workplace.

MySQL Tips and Tricks: Find out who is doing what in MySQL and how to kill the process, create binary log files, connect, create and select with Perl and Java, remove duplicates in a table with the index command, rollback and how to apply, merging several tables into one, updating foreign keys, monitor port 3306 with the tcpdump command, creating a C API, complex selects, and much more.

Create a Live Linux CD - BusyBox and OpenSSH Included: These steps will show you how to create a functioning Linux system, with the latest 2.6 kernel compiled from source, and how to integrate the BusyBox utilities including the installation of DHCP. Plus, how to compile in the OpenSSH package on this CD based system. On system boot-up a filesystem will be created and the contents from the CD will be uncompressed and completely loaded into RAM -- the CD could be removed at this point for boot-up on a second computer. The remaining functioning system will have full ssh capabilities. You can take over any PC assuming, of course, you have configured the kernel with the appropriate drivers and the PC can boot from a CD. This tutorial steps you through the whole processes.

SQLite Tutorial : This article explores the power and simplicity of sqlite3, first by starting with common commands and triggers, then the attach statement with the union operation is introduced in a way that allows multiple tables, in separate databases, to be combined as one virtual table, without the overhead of copying or moving data. Next, the simple sign function and the amazingly powerful trick of using this function in SQL select statements to solve complex queries with a single pass through the data is demonstrated, after making a brief mathematical case for how the sign function defines the absolute value and IF conditions.

The Lemon Parser Tutorial: This article explains how to build grammars and programs using the lemon parser, which is faster than yacc. And, unlike yacc, it is thread safe.

How to Compile the 2.6 kernel for Red Hat 9 and 8.0 and get Fedora Updates: This is a step by step tutorial on how to compile the 2.6 kernel from source.

Virtual Filesystem: Building A Linux Filesystem From An Ordinary File. You can take a disk file, format it as ext2, ext3, or reiser filesystem and then mount it, just like a physical drive. Yes, it then possible to read and write files to this newly mounted device. You can also copy the complete filesystem, since it is just a file, to another computer. If security is an issue, read on. This article will show you how to encrypt the filesystem, and mount it with ACL (Access Control Lists), which give you rights beyond the traditional read (r) write (w) and execute (x) for the 3 user groups file, owner and other.

Working With Time: What? There are 61 seconds in a minute? We can go back in time? We still tell time by the sun?



Chirico img Mike Chirico, a father of triplets (all girls) lives outside of Philadelphia, PA, USA. He has worked with Linux since 1996, has a Masters in Computer Science and Mathematics from Villanova University, and has worked in computer-related jobs from Wall Street to the University of Pennsylvania. His hero is Paul Erdos, a brilliant number theorist who was known for his open collaboration with others.


Mike's notes page is souptonuts. For open source consulting needs, please send an email to mchirico@gmail.com. All consulting work must include a donation to SourceForge.net.

SourceForge.net Logo


SourceForge.net Logo