Newer
Older
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputListener;
/**
* Represent the GUI part of a {@link Nonogram}
*/
public class NonogramComponent extends Component implements MouseInputListener {
/**
*
*/
private static final long serialVersionUID = 2252313796820615010L;
private static final int PIXELS_PER_SQUARE = 16;
private int width;
private int height;
private boolean[][] pixels;
/**
* Create a graphical representation of a Nonogram
* @param width The width in pixels of the Nonogram
* @param height The height in pixels of the Nonogram
*/
public NonogramComponent(int width, int height) {
this.width = width;
this.height = height;
pixels = new boolean[width][height];
listeners = new ArrayList<NonogramEventListener>();
addMouseMotionListener(this);
setPreferredSize(new Dimension(width*PIXELS_PER_SQUARE+1, height*PIXELS_PER_SQUARE+1));
}
/**
* Add an object that will be notified when events happen
* @param listener The objec to notify
*/
public void addListener(NonogramEventListener listener) {
listeners.add(listener);
}
/**
* Set a pixel to white or black
* @param x The x coordinate of the pixel to set
* @param y The y coordinate of the pixel to set
* @param val Set to black if true, otherwise set to white
*/
public void setPixel(int x, int y, boolean val) {
pixels[x][y] = val;
repaint();
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (pixels[x][y]) {
g2.setColor(Color.BLACK);
} else {
g2.setColor(Color.WHITE);
}
g2.fillRect(x*PIXELS_PER_SQUARE, y*PIXELS_PER_SQUARE, PIXELS_PER_SQUARE, PIXELS_PER_SQUARE);
}
}
g2.setColor(Color.BLACK);
for (int x = 0; x <= width; x++) {
g2.drawLine(x*PIXELS_PER_SQUARE, 0, x*PIXELS_PER_SQUARE, width*PIXELS_PER_SQUARE);
}
for (int y = 0; y <= width; y++) {
g2.drawLine(0, y*PIXELS_PER_SQUARE, height*PIXELS_PER_SQUARE, y*PIXELS_PER_SQUARE);
}
}
private void mouseUpdate(MouseEvent e) {
boolean left = SwingUtilities.isLeftMouseButton(e);
boolean right = SwingUtilities.isRightMouseButton(e);
int x = e.getX() / PIXELS_PER_SQUARE;
int y = e.getY() / PIXELS_PER_SQUARE;
if ((left || right) && x < width && y < height && x >= 0 && y >= 0) {
for (NonogramEventListener listener : listeners) {
listener.nonogramClicked(x, y, left);
}
}
}
@Override
public void mouseDragged(MouseEvent e) {
mouseUpdate(e);
}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {
mouseUpdate(e);
}
@Override
public void mouseReleased(MouseEvent e) {}