PaintShape.java

From EDM2
Jump to: navigation, search

From: Into Java - Part XVI

import java.awt.*;

public class PaintShape {
    private boolean filledShape;
    private Color paintColor;
    private int shape;
    private int startX;
    private int startY;
    private int stopX;
    private int stopY;
    private Rectangle rect;

    public PaintShape(boolean filled, Color c,
                        int sh, int x, int y) {
        filledShape = filled;
        paintColor = c;
        shape = sh;
        startX = x;
        startY = y;
    }

    public void setStop(int x, int y) {
        stopX = x;
        stopY = y;

        int xS, wid, yS, hig; // speedy declarations
        if (startX < stopX) {
            xS = startX;
            wid = stopX - startX;
        } else {
            xS = stopX;       // avoid negative width
            wid = startX - stopX;
        }
        if (startY < stopY) {
            yS = startY;
            hig = stopY - startY;
        } else {
            yS = stopY;       // avoid negative height
            hig = startY - stopY;
        }
        /* make the rect bigger than shape itself */
        rect = new Rectangle(xS-1, yS-1, wid+2, hig+2);
    }

    public boolean contains(Point xy) {
        return rect.contains(xy);
    }

    public void paintComponent(Graphics g) {

        Color oldColor = g.getColor();
        g.setColor(paintColor);

        if (shape == PaintPanel.LINE) { // that is line
            g.drawLine(startX, startY, stopX, stopY);
        } else {
            /* make four temp variables to avoid trouble */
            int startXX = startX;
            int startYY = startY;
            int width = stopX - startX;
            int height = stopY - startY;
            if (width < 0) { // not good
                startXX = stopX;
                width = -width;
            } else {
                startXX = startX;
            }
            if (height < 0) { // not good
                startYY = stopY;
                height = -height;
            } else {
                startYY = startY;
            }

            if (shape == PaintPanel.RECTANGLE) { // that is rectangle
                if (filledShape) {
                    g.fillRect(startXX, startYY, width, height);
                } else {
                    g.drawRect(startXX, startYY, width, height);
                }
            } else { // remaining is oval
                if (filledShape) {
                    g.fillOval(startXX, startYY, width, height);
                } else {
                    g.drawOval(startXX, startYY, width, height);
                }
            }
        }
        g.setColor(oldColor);
    }
}