ScalingGridPanel.java

package ac.essex.ooechs.imaging.commons.util.panels; 
 
import ac.essex.ooechs.imaging.commons.util.Region; 
import ac.essex.ooechs.imaging.commons.grids.Grid; 
 
import java.awt.*; 
import java.awt.event.*; 
 
/** 
 * <p/> 
 * This program is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation; either version 2 
 * of the License, or (at your option) any later version, 
 * provided that any use properly credits the author. 
 * This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details at http://www.gnu.org 
 * </p> 
 * 
 * @author Olly Oechsle, University of Essex, Date: 23-Oct-2006 
 * @version 1.0 
 */ 
public class ScalingGridPanel extends ScalingImagePanel { 
 
    Grid grid; 
 
    public int x = 0; 
    public int y = 0; 
 
    public ScalingGridPanel(Grid g) { 
 
        this.grid = g; 
 
        addMouseMotionListener(new MouseMotionAdapter() { 
            public void mouseMoved(MouseEvent e) { 
 
 
                int cellWidth = getWidth() / grid.getTotalHorizontalLines(); 
                int cellHeight = getHeight() / grid.getTotalVerticalLines(); 
 
                int gridX =  (e.getX() / cellWidth); 
                int gridY = (e.getY() / cellHeight); 
 
                if (x != gridX || y != gridY) { 
                    x = gridX; 
                    y = gridY; 
 
                    repaint(); 
                } 
 
            } 
        }); 
    } 
 
    public void paintComponent(Graphics g) { 
        super.paintComponent(g); 
 
        Region r = new Region(0, 0, getWidth(), getHeight()); 
 
        g.setColor(Color.WHITE); 
        grid.draw(g, r); 
 
        int cellWidth = getWidth() / grid.getTotalHorizontalLines(); 
        int cellHeight = getHeight() / grid.getTotalVerticalLines(); 
 
        // drawPixels a black box 
        g.setColor(Color.BLACK); 
        g.drawRect(x * cellWidth, y * cellHeight, cellWidth, cellHeight); 
 
        // and display coordinates 
        double xPos = (x + 0.1) * cellWidth; 
        double yPos = (y + 0.7) * cellHeight; 
        g.drawString(x + ", " + y, (int) xPos, (int) yPos); 
    } 
}