Example usage for java.awt Graphics drawString

List of usage examples for java.awt Graphics drawString

Introduction

In this page you can find the example usage for java.awt Graphics drawString.

Prototype

public abstract void drawString(AttributedCharacterIterator iterator, int x, int y);

Source Link

Document

Renders the text of the specified iterator applying its attributes in accordance with the specification of the java.awt.font.TextAttribute TextAttribute class.

Usage

From source file:se.llbit.chunky.renderer.scene.Scene.java

/**
 * Update the canvas - draw the latest rendered frame
 * @param warningText//from w w w . ja v  a2  s  .  c om
 */
public synchronized void updateCanvas(String warningText) {
    finalized = false;

    try {
        // flip buffers
        BufferedImage tmp = buffer;
        buffer = backBuffer;
        backBuffer = tmp;

        bufferData = ((DataBufferInt) backBuffer.getRaster().getDataBuffer()).getData();

        Graphics g = buffer.getGraphics();

        if (!warningText.isEmpty()) {
            g.setColor(java.awt.Color.red);
            int x0 = width / 2;
            int y0 = height / 2;
            g.setFont(infoFont);
            if (fontMetrics == null) {
                fontMetrics = g.getFontMetrics();
            }
            g.drawString(warningText, x0 - fontMetrics.stringWidth(warningText) / 2, y0);
        } else {

            if (renderState == RenderState.PREVIEW) {
                int x0 = width / 2;
                int y0 = height / 2;
                g.setColor(java.awt.Color.white);
                g.drawLine(x0, y0 - 4, x0, y0 + 4);
                g.drawLine(x0 - 4, y0, x0 + 4, y0);
                g.setFont(infoFont);
                Ray ray = new Ray();
                if (trace(ray) && ray.getCurrentMaterial() instanceof Block) {
                    Block block = (Block) ray.getCurrentMaterial();
                    g.drawString(String.format("target: %.2f m", ray.distance), 5, height - 18);
                    g.drawString(String.format("[0x%08X] %s (%s)", ray.getCurrentData(), block,
                            block.description(ray.getBlockData())), 5, height - 5);
                }
                Vector3d pos = camera.getPosition();
                g.drawString(String.format("(%.1f, %.1f, %.1f)", pos.x, pos.y, pos.z), 5, 11);
            }
        }

        g.dispose();
    } catch (IllegalStateException e) {
        Log.error("Unexpected exception while rendering back buffer", e);
    }
}

From source file:org.prom5.analysis.performance.dottedchart.ui.DottedChartPanel.java

public void redrawTitle(int xPos) {
    Graphics g = this.getGraphics();
    Color fgColor = null;//ww  w .j av a 2 s  . co m
    Color bgColor = null;
    Color tmpColor = null;
    fgColor = null;
    bgColor = null;
    // calculate common coordinates
    int yTop = border;

    // initialze start color
    fgColor = colorLogDark;
    bgColor = colorLogBright;

    // calculate current top
    int currentTop = yTop;

    // paint actual log lane (only the part in the clipping range determined)
    Iterator itr = dcModel.getSortedKeySetList().iterator();
    g.setFont(new Font("Dialog", Font.BOLD, 13));
    int index = 0;
    currentTop = yTop;
    while (itr.hasNext()) {
        String dimName = (String) itr.next();
        if (dcModel.getTypeHashMap().equals(ST_INST) && !dcModel.getInstanceTypeToKeep().contains(dimName))
            continue;

        //         g.setColor(fgColor);
        g.setColor(Color.black);
        g.drawString(dimName, xPos + 5, currentTop + 20);

        index++;
        currentTop = unit2Cord(index);

        // swap colors
        tmpColor = fgColor;
        fgColor = bgColor;
        bgColor = tmpColor;
    }

}

From source file:org.processmining.analysis.performance.advanceddottedchartanalysis.ui.DottedChartPanel.java

protected void drawVerticalLines(Graphics g, int imageWidth, int imageHeight) {
    int pixStart = 0;
    int yTop = BORDER;
    int yBottom = imageHeight - BORDER;
    String dateStr, timeStr;/*from w  w  w .j ava 2 s  .  c o  m*/
    // adjust width
    adjustWidth();

    long timeStart = 0;
    if (dcop.getTimeOption().equals(DottedChartModel.TIME_ACTUAL)) {
        timeStart = dcModel.getLogMinValueforScreen();
    }
    long lastLable = Long.MIN_VALUE;
    long clipRightTs = coUtil.coord2timeMillis(coUtil.getClipR());

    for (; timeStart < clipRightTs; timeStart += dca.getDottedChartOptionPanel().getWidthDivider()) {
        pixStart = coUtil.time2coord(timeStart) + BORDER;
        cal.setTimeInMillis(timeStart - timeOffset);
        g.setColor(colorTimeLine);
        g.drawLine(pixStart, yTop, pixStart, yBottom);
        g.setColor(dca.getSettingPanel().getFBcolor());
        g.setColor(Color.black); // to be deleted

        if (dcop.getTimeOption().equals(DottedChartModel.TIME_ACTUAL)) {
            // if(lastLable+80>=pixStart+2) continue;
            // timeStr = String.valueOf(timeStart);
            // g.drawString(timeStr, pixStart+2, yTop);

            if (lastLable + 80 >= pixStart + 2)
                continue;
            dateStr = cal.get(Calendar.DAY_OF_MONTH) + "." + (cal.get(Calendar.MONTH) + 1) + "."
                    + cal.get(Calendar.YEAR);
            g.drawString(dateStr, pixStart + 2, yTop);
            timeStr = cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":"
                    + cal.get(Calendar.SECOND);
            g.drawString(timeStr, pixStart + 2, yTop + 10);
        } else if (dcop.getTimeOption().equals(DottedChartModel.TIME_RELATIVE_TIME)) {
            if (lastLable + 80 >= pixStart + 2)
                continue;
            long days = timeStart / 1000 / 60 / 60 / 24;
            long hours = (timeStart - days * 24 * 60 * 60 * 1000) / 1000 / 60 / 60;
            long minutes = (timeStart - days * 24 * 60 * 60 * 1000 - hours * 60 * 60 * 1000) / 1000 / 60;
            long seconds = (timeStart - days * 24 * 60 * 60 * 1000 - hours * 60 * 60 * 1000
                    - minutes * 60 * 1000) / 1000;
            timeStr = days + "days:" + hours + ":" + minutes + ":" + seconds;
            g.drawString(timeStr, pixStart + 2, yTop);
        } else if (dcop.getTimeOption().equals(DottedChartModel.TIME_RELATIVE_RATIO)) {
            if (lastLable + 40 >= pixStart + 2)
                continue;
            timeStr = timeStart / 100 + "." + (timeStart - timeStart / 100 * 100) + "%";
            g.drawString(timeStr, pixStart + 2, yTop);
        } else if (dcop.getTimeOption().equals(DottedChartModel.TIME_LOGICAL)
                || dcop.getTimeOption().equals(DottedChartModel.TIME_LOGICAL_RELATIVE)) {
            if (lastLable + 20 >= pixStart + 2)
                continue;
            timeStr = String.valueOf(timeStart);
            g.drawString(timeStr, pixStart + 2, yTop);
        }
        lastLable = pixStart + 2;
    }
}

From source file:org.processmining.analysis.performance.dottedchart.ui.DottedChartPanel.java

public void redrawTitle(int xPos) {
    Graphics g = this.getGraphics();
    Color fgColor = null;//  w w  w .j ava2 s.co m
    Color bgColor = null;
    Color tmpColor = null;
    fgColor = null;
    bgColor = null;
    // calculate common coordinates
    int yTop = border;

    // initialze start color
    fgColor = colorLogDark;
    bgColor = colorLogBright;

    // calculate current top
    int currentTop = yTop;

    // paint actual log lane (only the part in the clipping range
    // determined)
    Iterator itr = dcModel.getSortedKeySetList().iterator();
    g.setFont(new Font("Dialog", Font.BOLD, 13));
    int index = 0;
    currentTop = yTop;
    while (itr.hasNext()) {
        String dimName = (String) itr.next();
        if (dcModel.getTypeHashMap().equals(ST_INST) && !dcModel.getInstanceTypeToKeep().contains(dimName))
            continue;

        // g.setColor(fgColor);
        g.setColor(Color.black);
        g.drawString(dimName, xPos + 5, currentTop + 20);

        index++;
        currentTop = unit2Cord(index);

        // swap colors
        tmpColor = fgColor;
        fgColor = bgColor;
        bgColor = tmpColor;
    }

}

From source file:org.prom5.analysis.performance.advanceddottedchartanalysis.ui.DottedChartPanel.java

protected void drawVerticalLines(Graphics g, int imageWidth, int imageHeight) {
    int pixStart = 0;
    int yTop = BORDER;
    int yBottom = imageHeight - BORDER;
    String dateStr, timeStr;//from   w ww  .  j  ava 2  s  . c  o  m
    // adjust width
    adjustWidth();

    long timeStart = 0;
    if (dcop.getTimeOption().equals(DottedChartModel.TIME_ACTUAL)) {
        timeStart = dcModel.getLogMinValueforScreen();
    }
    long lastLable = Long.MIN_VALUE;
    long clipRightTs = coUtil.coord2timeMillis(coUtil.getClipR());

    for (; timeStart < clipRightTs; timeStart += dca.getDottedChartOptionPanel().getWidthDivider()) {
        pixStart = coUtil.time2coord(timeStart) + BORDER;
        cal.setTimeInMillis(timeStart - timeOffset);
        g.setColor(colorTimeLine);
        g.drawLine(pixStart, yTop, pixStart, yBottom);
        g.setColor(dca.getSettingPanel().getFBcolor());
        g.setColor(Color.black); // to be deleted

        if (dcop.getTimeOption().equals(DottedChartModel.TIME_ACTUAL)) {
            //            if(lastLable+80>=pixStart+2) continue;
            //            timeStr = String.valueOf(timeStart);
            //            g.drawString(timeStr, pixStart+2, yTop);

            if (lastLable + 80 >= pixStart + 2)
                continue;
            dateStr = cal.get(Calendar.DAY_OF_MONTH) + "." + (cal.get(Calendar.MONTH) + 1) + "."
                    + cal.get(Calendar.YEAR);
            g.drawString(dateStr, pixStart + 2, yTop);
            timeStr = cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":"
                    + cal.get(Calendar.SECOND);
            g.drawString(timeStr, pixStart + 2, yTop + 10);
        } else if (dcop.getTimeOption().equals(DottedChartModel.TIME_RELATIVE_TIME)) {
            if (lastLable + 80 >= pixStart + 2)
                continue;
            long days = timeStart / 1000 / 60 / 60 / 24;
            long hours = (timeStart - days * 24 * 60 * 60 * 1000) / 1000 / 60 / 60;
            long minutes = (timeStart - days * 24 * 60 * 60 * 1000 - hours * 60 * 60 * 1000) / 1000 / 60;
            long seconds = (timeStart - days * 24 * 60 * 60 * 1000 - hours * 60 * 60 * 1000
                    - minutes * 60 * 1000) / 1000;
            timeStr = days + "days:" + hours + ":" + minutes + ":" + seconds;
            g.drawString(timeStr, pixStart + 2, yTop);
        } else if (dcop.getTimeOption().equals(DottedChartModel.TIME_RELATIVE_RATIO)) {
            if (lastLable + 40 >= pixStart + 2)
                continue;
            timeStr = timeStart / 100 + "." + (timeStart - timeStart / 100 * 100) + "%";
            g.drawString(timeStr, pixStart + 2, yTop);
        } else if (dcop.getTimeOption().equals(DottedChartModel.TIME_LOGICAL)
                || dcop.getTimeOption().equals(DottedChartModel.TIME_LOGICAL_RELATIVE)) {
            if (lastLable + 20 >= pixStart + 2)
                continue;
            timeStr = String.valueOf(timeStart);
            g.drawString(timeStr, pixStart + 2, yTop);
        }
        lastLable = pixStart + 2;
    }
}

From source file:uk.ac.babraham.BamQC.Graphs.ScatterGraph.java

@Override
protected void paintComponent(Graphics g) {

    g.setColor(Color.WHITE);/*from   w ww  .  ja  v a2  s . c  o  m*/
    g.fillRect(0, 0, getWidth(), getHeight());
    g.setColor(Color.BLACK);

    if (g instanceof Graphics2D) {
        ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }

    double yStart, xStart;
    if (minY % yInterval == 0) {
        yStart = minY;
    } else {
        yStart = yInterval * (((int) minY / yInterval) + 1);
    }

    if (minX % xInterval == 0) {
        xStart = minX;
    } else {
        xStart = xInterval * (((int) minX / xInterval) + 1);
    }

    int xOffset = 0;

    // Draw the yLabel on the left of the yAxis
    int yLabelRightShift = 12;
    if (yLabel == null || yLabel.isEmpty()) {
        yLabelRightShift = 0;
    } else {
        if (g instanceof Graphics2D) {
            Graphics2D g2 = (Graphics2D) g;
            AffineTransform orig = g2.getTransform();
            g2.rotate(-Math.PI / 2);
            g2.setColor(Color.BLACK);
            g2.drawString(yLabel, -getY(-yInterval) / 2 - (g.getFontMetrics().stringWidth(yLabel) / 2),
                    yLabelRightShift);
            g2.setTransform(orig);
        }
    }

    // Draw the y axis labels
    int lastYLabelEnd = Integer.MAX_VALUE;
    for (double i = yStart; i <= maxY; i += yInterval) {
        String label = "" + i;
        label = label.replaceAll(".0$", ""); // Don't leave trailing .0s where we don't need them.
        // Calculate the new xOffset depending on the widest ylabel.
        int width = g.getFontMetrics().stringWidth(label);
        if (width > xOffset) {
            xOffset = width;
        }
        // place the y axis labels so that they don't overlap when the plot is resized.
        int baseNumberHeight = g.getFontMetrics().getHeight();
        int baseNumberPosition = getY(i) + (baseNumberHeight / 2);
        if (baseNumberPosition + baseNumberHeight < lastYLabelEnd) {
            // Draw the y axis labels
            g.drawString(label, yLabelRightShift + 6, baseNumberPosition);
            lastYLabelEnd = baseNumberPosition + 2;
        }
    }

    // Give the x axis a bit of breathing space
    xOffset = xOffset + yLabelRightShift + 8;

    // Now draw horizontal lines across from the y axis
    g.setColor(new Color(180, 180, 180));
    for (double i = yStart; i <= maxY; i += yInterval) {
        g.drawLine(xOffset, getY(i), getWidth() - 10, getY(i));
    }
    g.setColor(Color.BLACK);

    // Draw the graph title
    int titleWidth = g.getFontMetrics().stringWidth(graphTitle);
    g.drawString(graphTitle, (xOffset + ((getWidth() - (xOffset + 10)) / 2)) - (titleWidth / 2), 30);

    // Draw the xLabel under the xAxis
    g.drawString(xLabel, (getWidth() / 2) - (g.getFontMetrics().stringWidth(xLabel) / 2), getHeight() - 5);

    // Now draw the data points
    double baseWidth = (getWidth() - (xOffset + 10)) / (maxX - minX);

    //      System.out.println("Base Width is "+baseWidth);
    // Let's find the longest label, and then work out how often we can draw labels
    int lastXLabelEnd = 0;

    // Draw the x axis labels
    for (double i = xStart; i <= maxX; i += xInterval) {
        g.setColor(Color.BLACK);
        String baseNumber = "" + i;
        baseNumber = baseNumber.replaceAll(".0$", ""); // Don't leave trailing .0s where we don't need them.
        // Calculate the new xOffset depending on the widest ylabel.
        int baseNumberWidth = g.getFontMetrics().stringWidth(baseNumber);
        int baseNumberPosition = (int) (xOffset + (baseWidth * i) - (baseNumberWidth / 2));

        if (baseNumberPosition > lastXLabelEnd) {
            g.drawString(baseNumber, baseNumberPosition, getHeight() - 25);
            lastXLabelEnd = baseNumberPosition + baseNumberWidth + 5;
        }
        // Now draw vertical lines across from the y axis
        g.setColor(new Color(180, 180, 180));
        g.drawLine((int) (xOffset + (baseWidth * i)), getHeight() - 40, (int) (xOffset + (baseWidth * i)), 40);
        g.setColor(Color.BLACK);
    }

    // Now draw the axes
    g.drawLine(xOffset, getHeight() - 40, getWidth() - 10, getHeight() - 40);
    g.drawLine(xOffset, getHeight() - 40, xOffset, 40);

    // Initialise the arrays containing the tooltips
    rectangles = new ArrayList<Rectangle>();
    tips = new ArrayList<String>();

    g.setColor(Color.BLUE);
    // Draw the data points
    double ovalSize = 5;
    // We distinguish two inputs since the x label does not start from 0.
    // used for computing the actual line points as if they were starting from 0.
    double[] inputVar = new double[data.length];
    double[] responseVar = new double[data.length];
    for (int d = 0; d < data.length; d++) {
        double x = getX(xCategories[d], xOffset) - ovalSize / 2;
        double y = getY(data[d]) - ovalSize / 2;
        g.fillOval((int) x, (int) y, (int) (ovalSize), (int) (ovalSize));
        g.drawString(toolTipLabels[d], (int) x + 2, (int) y + 16);
        inputVar[d] = Double.valueOf(xCategories[d]);
        responseVar[d] = data[d];

        // Tool tips
        Rectangle r = new Rectangle((int) x, (int) y, (int) (ovalSize), (int) (ovalSize));
        rectangles.add(r);
        tips.add(toolTipLabels[d]);
    }
    g.setColor(Color.BLACK);

    // Draw the intercept 

    // WARNING: Is drawing a least squares regression line asserting that "the distribution follows a power law" correct?
    // This is our case if we plot log-log..
    // It seems not in this paper (Appendix A) http://arxiv.org/pdf/0706.1062v2.pdf

    if (data.length > 1) {
        LinearRegression linReg = new LinearRegression(inputVar, responseVar);
        double intercept = linReg.intercept();
        double slope = linReg.slope();
        double rSquare = linReg.R2();

        // Let's now calculate the two points (x1, y1) and (xn, yn)
        // (x1, y1). We need to skip the areas where x1<minY and y1>maxY
        double x1 = minX;
        double y1 = slope * minX + intercept;
        if (y1 < minY) {
            x1 = (minY - intercept) / slope;
            y1 = minY;
        } else if (y1 > maxY) {
            x1 = (maxY - intercept) / slope;
            y1 = maxY;
        }
        // (xn, yn). maxX which essentially is inputVar[inputVar.length-1]
        double xn = maxX;
        double yn = slope * maxX + intercept;

        if (g instanceof Graphics2D) {
            ((Graphics2D) g).setStroke(new BasicStroke(1.5f));
        }
        g.setColor(Color.RED);
        g.drawLine(getX(x1, xOffset), getY(y1), getX(xn, xOffset), getY(yn));
        g.setColor(Color.BLACK);
        if (g instanceof Graphics2D) {
            ((Graphics2D) g).setStroke(new BasicStroke(1));
        }

        // Draw the legend for the intercept
        String legendString = "y = " + Precision.round(slope, 3) + "x";
        if (intercept < 0)
            legendString += " - " + Precision.round(-intercept, 3);
        else
            legendString += " + " + Precision.round(intercept, 3);
        int width = g.getFontMetrics().stringWidth(legendString);

        // First draw a box to put the legend in
        g.setColor(Color.WHITE);
        g.fillRect(xOffset + 10, 45, width + 8, 35);
        g.setColor(Color.LIGHT_GRAY);
        g.drawRect(xOffset + 10, 45, width + 8, 35);

        // Now draw the legend label
        g.setColor(Color.RED);
        g.drawString(legendString, xOffset + 13, 60);
        g.drawString("R^2 = " + Precision.round(rSquare, 3), xOffset + 13, 76);
        g.setColor(Color.BLACK);
    }

}

From source file:net.pms.dlna.DLNAMediaInfo.java

public void parse(InputFile inputFile, Format ext, int type, boolean thumbOnly) {
    int i = 0;//from  w ww .  j  av  a2  s.co  m

    while (isParsing()) {
        if (i == 5) {
            setMediaparsed(true);
            break;
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }

        i++;
    }

    if (isMediaparsed()) {
        return;
    }

    if (inputFile != null) {
        if (inputFile.getFile() != null) {
            setSize(inputFile.getFile().length());
        } else {
            setSize(inputFile.getSize());
        }

        ProcessWrapperImpl pw = null;
        boolean ffmpeg_parsing = true;

        if (type == Format.AUDIO || ext instanceof AudioAsVideo) {
            ffmpeg_parsing = false;
            DLNAMediaAudio audio = new DLNAMediaAudio();

            if (inputFile.getFile() != null) {
                try {
                    AudioFile af = AudioFileIO.read(inputFile.getFile());
                    AudioHeader ah = af.getAudioHeader();

                    if (ah != null && !thumbOnly) {
                        int length = ah.getTrackLength();
                        int rate = ah.getSampleRateAsNumber();

                        if (ah.getEncodingType().toLowerCase().contains("flac 24")) {
                            audio.setBitsperSample(24);
                        }

                        audio.setSampleFrequency("" + rate);
                        setDuration((double) length);
                        setBitrate((int) ah.getBitRateAsNumber());
                        audio.getAudioProperties().setNumberOfChannels(2);

                        if (ah.getChannels() != null && ah.getChannels().toLowerCase().contains("mono")) {
                            audio.getAudioProperties().setNumberOfChannels(1);
                        } else if (ah.getChannels() != null
                                && ah.getChannels().toLowerCase().contains("stereo")) {
                            audio.getAudioProperties().setNumberOfChannels(2);
                        } else if (ah.getChannels() != null) {
                            audio.getAudioProperties().setNumberOfChannels(Integer.parseInt(ah.getChannels()));
                        }

                        audio.setCodecA(ah.getEncodingType().toLowerCase());

                        if (audio.getCodecA().contains("(windows media")) {
                            audio.setCodecA(audio.getCodecA()
                                    .substring(0, audio.getCodecA().indexOf("(windows media")).trim());
                        }
                    }

                    Tag t = af.getTag();

                    if (t != null) {
                        if (t.getArtworkList().size() > 0) {
                            setThumb(t.getArtworkList().get(0).getBinaryData());
                        } else {
                            if (configuration.getAudioThumbnailMethod() > 0) {
                                setThumb(CoverUtil.get().getThumbnailFromArtistAlbum(
                                        configuration.getAudioThumbnailMethod() == 1 ? CoverUtil.AUDIO_AMAZON
                                                : CoverUtil.AUDIO_DISCOGS,
                                        audio.getArtist(), audio.getAlbum()));
                            }
                        }

                        if (!thumbOnly) {
                            audio.setAlbum(t.getFirst(FieldKey.ALBUM));
                            audio.setArtist(t.getFirst(FieldKey.ARTIST));
                            audio.setSongname(t.getFirst(FieldKey.TITLE));
                            String y = t.getFirst(FieldKey.YEAR);

                            try {
                                if (y.length() > 4) {
                                    y = y.substring(0, 4);
                                }
                                audio.setYear(Integer.parseInt(((y != null && y.length() > 0) ? y : "0")));
                                y = t.getFirst(FieldKey.TRACK);
                                audio.setTrack(Integer.parseInt(((y != null && y.length() > 0) ? y : "1")));
                                audio.setGenre(t.getFirst(FieldKey.GENRE));
                            } catch (Throwable e) {
                                logger.debug("Error parsing unimportant metadata: " + e.getMessage());
                            }
                        }
                    }
                } catch (Throwable e) {
                    logger.debug("Error parsing audio file: {} - {}", e.getMessage(),
                            e.getCause() != null ? e.getCause().getMessage() : "");
                    ffmpeg_parsing = false;
                }

                if (audio.getSongname() == null || audio.getSongname().length() == 0) {
                    audio.setSongname(inputFile.getFile().getName());
                }

                if (!ffmpeg_parsing) {
                    getAudioTracksList().add(audio);
                }
            }
        }

        if (type == Format.IMAGE && inputFile.getFile() != null) {
            try {
                ffmpeg_parsing = false;
                ImageInfo info = Sanselan.getImageInfo(inputFile.getFile());
                setWidth(info.getWidth());
                setHeight(info.getHeight());
                setBitsPerPixel(info.getBitsPerPixel());
                String formatName = info.getFormatName();

                if (formatName.startsWith("JPEG")) {
                    setCodecV("jpg");
                    IImageMetadata meta = Sanselan.getMetadata(inputFile.getFile());

                    if (meta != null && meta instanceof JpegImageMetadata) {
                        JpegImageMetadata jpegmeta = (JpegImageMetadata) meta;
                        TiffField tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_MODEL);

                        if (tf != null) {
                            setModel(tf.getStringValue().trim());
                        }

                        tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_EXPOSURE_TIME);
                        if (tf != null) {
                            setExposure((int) (1000 * tf.getDoubleValue()));
                        }

                        tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_ORIENTATION);
                        if (tf != null) {
                            setOrientation(tf.getIntValue());
                        }

                        tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_ISO);
                        if (tf != null) {
                            // Galaxy Nexus jpg pictures may contain multiple values, take the first
                            int[] isoValues = tf.getIntArrayValue();
                            setIso(isoValues[0]);
                        }
                    }
                } else if (formatName.startsWith("PNG")) {
                    setCodecV("png");
                } else if (formatName.startsWith("GIF")) {
                    setCodecV("gif");
                } else if (formatName.startsWith("TIF")) {
                    setCodecV("tiff");
                }

                setContainer(getCodecV());
            } catch (Throwable e) {
                logger.info("Error parsing image ({}) with Sanselan, switching to FFmpeg.",
                        inputFile.getFile().getAbsolutePath());
            }
        }

        if (configuration.getImageThumbnailsEnabled() && type != Format.VIDEO && type != Format.AUDIO) {
            try {
                File thumbDir = new File(configuration.getTempFolder(), THUMBNAIL_DIRECTORY_NAME);

                logger.trace("Generating thumbnail for: {}", inputFile.getFile().getAbsolutePath());

                if (!thumbDir.exists() && !thumbDir.mkdirs()) {
                    logger.warn("Could not create thumbnail directory: {}", thumbDir.getAbsolutePath());
                } else {
                    File thumbFile = new File(thumbDir, inputFile.getFile().getName() + ".jpg");
                    String thumbFilename = thumbFile.getAbsolutePath();

                    logger.trace("Creating (temporary) thumbnail: {}", thumbFilename);

                    // Create the thumbnail image using the Thumbnailator library
                    final Builder<File> thumbnail = Thumbnails.of(inputFile.getFile());
                    thumbnail.size(320, 180);
                    thumbnail.outputFormat("jpg");
                    thumbnail.outputQuality(1.0f);

                    try {
                        thumbnail.toFile(thumbFilename);
                    } catch (IIOException e) {
                        logger.debug("Error generating thumbnail for: " + inputFile.getFile().getName());
                        logger.debug("The full error was: " + e);
                    }

                    File jpg = new File(thumbFilename);

                    if (jpg.exists()) {
                        InputStream is = new FileInputStream(jpg);
                        int sz = is.available();

                        if (sz > 0) {
                            setThumb(new byte[sz]);
                            is.read(getThumb());
                        }

                        is.close();

                        if (!jpg.delete()) {
                            jpg.deleteOnExit();
                        }
                    }
                }
            } catch (UnsupportedFormatException ufe) {
                logger.debug("Thumbnailator does not support the format of {}: {}",
                        inputFile.getFile().getAbsolutePath(), ufe.getMessage());
            } catch (Exception e) {
                logger.debug("Thumbnailator could not generate a thumbnail for: {}",
                        inputFile.getFile().getAbsolutePath(), e);
            }
        }

        if (ffmpeg_parsing) {
            if (!thumbOnly || !configuration.isUseMplayerForVideoThumbs()) {
                pw = getFFmpegThumbnail(inputFile);
            }

            String input = "-";
            boolean dvrms = false;

            if (inputFile.getFile() != null) {
                input = ProcessUtil.getShortFileNameIfWideChars(inputFile.getFile().getAbsolutePath());
                dvrms = inputFile.getFile().getAbsolutePath().toLowerCase().endsWith("dvr-ms");
            }

            if (!ffmpeg_failure && !thumbOnly) {
                if (input.equals("-")) {
                    input = "pipe:";
                }

                boolean matchs = false;
                ArrayList<String> lines = (ArrayList<String>) pw.getResults();
                int langId = 0;
                int subId = 0;
                ListIterator<String> FFmpegMetaData = lines.listIterator();

                for (String line : lines) {
                    FFmpegMetaData.next();
                    line = line.trim();
                    if (line.startsWith("Output")) {
                        matchs = false;
                    } else if (line.startsWith("Input")) {
                        if (line.indexOf(input) > -1) {
                            matchs = true;
                            setContainer(line.substring(10, line.indexOf(",", 11)).trim());
                        } else {
                            matchs = false;
                        }
                    } else if (matchs) {
                        if (line.indexOf("Duration") > -1) {
                            StringTokenizer st = new StringTokenizer(line, ",");
                            while (st.hasMoreTokens()) {
                                String token = st.nextToken().trim();
                                if (token.startsWith("Duration: ")) {
                                    String durationStr = token.substring(10);
                                    int l = durationStr.substring(durationStr.indexOf(".") + 1).length();
                                    if (l < 4) {
                                        durationStr = durationStr + "00".substring(0, 3 - l);
                                    }
                                    if (durationStr.indexOf("N/A") > -1) {
                                        setDuration(null);
                                    } else {
                                        setDuration(parseDurationString(durationStr));
                                    }
                                } else if (token.startsWith("bitrate: ")) {
                                    String bitr = token.substring(9);
                                    int spacepos = bitr.indexOf(" ");
                                    if (spacepos > -1) {
                                        String value = bitr.substring(0, spacepos);
                                        String unit = bitr.substring(spacepos + 1);
                                        setBitrate(Integer.parseInt(value));
                                        if (unit.equals("kb/s")) {
                                            setBitrate(1024 * getBitrate());
                                        }
                                        if (unit.equals("mb/s")) {
                                            setBitrate(1048576 * getBitrate());
                                        }
                                    }
                                }
                            }
                        } else if (line.indexOf("Audio:") > -1) {
                            StringTokenizer st = new StringTokenizer(line, ",");
                            int a = line.indexOf("(");
                            int b = line.indexOf("):", a);
                            DLNAMediaAudio audio = new DLNAMediaAudio();
                            audio.setId(langId++);
                            if (a > -1 && b > a) {
                                audio.setLang(line.substring(a + 1, b));
                            } else {
                                audio.setLang(DLNAMediaLang.UND);
                            }

                            // Get TS IDs
                            a = line.indexOf("[0x");
                            b = line.indexOf("]", a);
                            if (a > -1 && b > a + 3) {
                                String idString = line.substring(a + 3, b);
                                try {
                                    audio.setId(Integer.parseInt(idString, 16));
                                } catch (NumberFormatException nfe) {
                                    logger.debug("Error parsing Stream ID: " + idString);
                                }
                            }

                            while (st.hasMoreTokens()) {
                                String token = st.nextToken().trim();
                                Integer nChannels;

                                if (token.startsWith("Stream")) {
                                    audio.setCodecA(token.substring(token.indexOf("Audio: ") + 7));
                                } else if (token.endsWith("Hz")) {
                                    audio.setSampleFrequency(token.substring(0, token.indexOf("Hz")).trim());
                                } else if ((nChannels = audioChannelLayout.get(token)) != null) {
                                    audio.getAudioProperties().setNumberOfChannels(nChannels);
                                } else if (token.matches("\\d+(?:\\s+channels?)")) { // implicitly anchored at both ends e.g. ^ ... $
                                    // setNumberOfChannels(String) parses the number out of the string
                                    audio.getAudioProperties().setNumberOfChannels(token);
                                } else if (token.equals("s32")) {
                                    audio.setBitsperSample(32);
                                } else if (token.equals("s24")) {
                                    audio.setBitsperSample(24);
                                } else if (token.equals("s16")) {
                                    audio.setBitsperSample(16);
                                }
                            }
                            int FFmpegMetaDataNr = FFmpegMetaData.nextIndex();

                            if (FFmpegMetaDataNr > -1) {
                                line = lines.get(FFmpegMetaDataNr);
                            }

                            if (line.indexOf("Metadata:") > -1) {
                                FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                line = lines.get(FFmpegMetaDataNr);
                                while (line.indexOf("      ") == 0) {
                                    if (line.toLowerCase().indexOf("title           :") > -1) {
                                        int aa = line.indexOf(": ");
                                        int bb = line.length();
                                        if (aa > -1 && bb > aa) {
                                            audio.setFlavor(line.substring(aa + 2, bb));
                                            break;
                                        }
                                    } else {
                                        FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                        line = lines.get(FFmpegMetaDataNr);
                                    }
                                }
                            }

                            getAudioTracksList().add(audio);
                        } else if (line.indexOf("Video:") > -1) {
                            StringTokenizer st = new StringTokenizer(line, ",");
                            while (st.hasMoreTokens()) {
                                String token = st.nextToken().trim();
                                if (token.startsWith("Stream")) {
                                    setCodecV(token.substring(token.indexOf("Video: ") + 7));
                                } else if ((token.indexOf("tbc") > -1 || token.indexOf("tb(c)") > -1)) {
                                    // A/V sync issues with newest FFmpeg, due to the new tbr/tbn/tbc outputs
                                    // Priority to tb(c)
                                    String frameRateDoubleString = token.substring(0, token.indexOf("tb"))
                                            .trim();
                                    try {
                                        if (!frameRateDoubleString.equals(getFrameRate())) {// tbc taken into account only if different than tbr
                                            Double frameRateDouble = Double.parseDouble(frameRateDoubleString);
                                            setFrameRate(
                                                    String.format(Locale.ENGLISH, "%.2f", frameRateDouble / 2));
                                        }
                                    } catch (NumberFormatException nfe) {
                                        // Could happen if tbc is "1k" or something like that, no big deal
                                        logger.debug(
                                                "Could not parse frame rate \"" + frameRateDoubleString + "\"");
                                    }

                                } else if ((token.indexOf("tbr") > -1 || token.indexOf("tb(r)") > -1)
                                        && getFrameRate() == null) {
                                    setFrameRate(token.substring(0, token.indexOf("tb")).trim());
                                } else if ((token.indexOf("fps") > -1 || token.indexOf("fps(r)") > -1)
                                        && getFrameRate() == null) { // dvr-ms ?
                                    setFrameRate(token.substring(0, token.indexOf("fps")).trim());
                                } else if (token.indexOf("x") > -1) {
                                    String resolution = token.trim();
                                    if (resolution.indexOf(" [") > -1) {
                                        resolution = resolution.substring(0, resolution.indexOf(" ["));
                                    }
                                    try {
                                        setWidth(Integer
                                                .parseInt(resolution.substring(0, resolution.indexOf("x"))));
                                    } catch (NumberFormatException nfe) {
                                        logger.debug("Could not parse width from \""
                                                + resolution.substring(0, resolution.indexOf("x")) + "\"");
                                    }
                                    try {
                                        setHeight(Integer
                                                .parseInt(resolution.substring(resolution.indexOf("x") + 1)));
                                    } catch (NumberFormatException nfe) {
                                        logger.debug("Could not parse height from \""
                                                + resolution.substring(resolution.indexOf("x") + 1) + "\"");
                                    }
                                }
                            }
                        } else if (line.indexOf("Subtitle:") > -1 && !line.contains("tx3g")) {
                            DLNAMediaSubtitle lang = new DLNAMediaSubtitle();
                            lang.setType((line.contains("dvdsub") && Platform.isWindows() ? SubtitleType.VOBSUB
                                    : SubtitleType.UNKNOWN));
                            int a = line.indexOf("(");
                            int b = line.indexOf("):", a);
                            if (a > -1 && b > a) {
                                lang.setLang(line.substring(a + 1, b));
                            } else {
                                lang.setLang(DLNAMediaLang.UND);
                            }

                            lang.setId(subId++);
                            int FFmpegMetaDataNr = FFmpegMetaData.nextIndex();

                            if (FFmpegMetaDataNr > -1) {
                                line = lines.get(FFmpegMetaDataNr);
                            }

                            if (line.indexOf("Metadata:") > -1) {
                                FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                line = lines.get(FFmpegMetaDataNr);

                                while (line.indexOf("      ") == 0) {
                                    if (line.toLowerCase().indexOf("title           :") > -1) {
                                        int aa = line.indexOf(": ");
                                        int bb = line.length();
                                        if (aa > -1 && bb > aa) {
                                            lang.setFlavor(line.substring(aa + 2, bb));
                                            break;
                                        }
                                    } else {
                                        FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                        line = lines.get(FFmpegMetaDataNr);
                                    }
                                }
                            }
                            getSubtitleTracksList().add(lang);
                        }
                    }
                }
            }

            if (!thumbOnly && getContainer() != null && inputFile.getFile() != null
                    && getContainer().equals("mpegts") && isH264() && getDurationInSeconds() == 0) {
                // Parse the duration
                try {
                    int length = MpegUtil.getDurationFromMpeg(inputFile.getFile());
                    if (length > 0) {
                        setDuration((double) length);
                    }
                } catch (IOException e) {
                    logger.trace("Error retrieving length: " + e.getMessage());
                }
            }

            if (configuration.isUseMplayerForVideoThumbs() && type == Format.VIDEO && !dvrms) {
                try {
                    getMplayerThumbnail(inputFile);
                    String frameName = "" + inputFile.hashCode();
                    frameName = configuration.getTempFolder() + "/mplayer_thumbs/" + frameName
                            + "00000001/00000001.jpg";
                    frameName = frameName.replace(',', '_');
                    File jpg = new File(frameName);

                    if (jpg.exists()) {
                        InputStream is = new FileInputStream(jpg);
                        int sz = is.available();

                        if (sz > 0) {
                            setThumb(new byte[sz]);
                            is.read(getThumb());
                        }

                        is.close();

                        if (!jpg.delete()) {
                            jpg.deleteOnExit();
                        }

                        // Try and retry
                        if (!jpg.getParentFile().delete() && !jpg.getParentFile().delete()) {
                            logger.debug("Failed to delete \"" + jpg.getParentFile().getAbsolutePath() + "\"");
                        }
                    }
                } catch (IOException e) {
                    logger.debug("Caught exception", e);
                }
            }

            if (type == Format.VIDEO && pw != null && getThumb() == null) {
                InputStream is;
                try {
                    is = pw.getInputStream(0);
                    int sz = is.available();
                    if (sz > 0) {
                        setThumb(new byte[sz]);
                        is.read(getThumb());
                    }
                    is.close();

                    if (sz > 0 && !net.pms.PMS.isHeadless()) {
                        BufferedImage image = ImageIO.read(new ByteArrayInputStream(getThumb()));
                        if (image != null) {
                            Graphics g = image.getGraphics();
                            g.setColor(Color.WHITE);
                            g.setFont(new Font("Arial", Font.PLAIN, 14));
                            int low = 0;
                            if (getWidth() > 0) {
                                if (getWidth() == 1920 || getWidth() == 1440) {
                                    g.drawString("1080p", 0, low += 18);
                                } else if (getWidth() == 1280) {
                                    g.drawString("720p", 0, low += 18);
                                }
                            }
                            ByteArrayOutputStream out = new ByteArrayOutputStream();
                            ImageIO.write(image, "jpeg", out);
                            setThumb(out.toByteArray());
                        }
                    }
                } catch (IOException e) {
                    logger.debug("Error while decoding thumbnail: " + e.getMessage());
                }
            }
        }

        finalize(type, inputFile);
        setMediaparsed(true);
    }
}

From source file:ClipDemo.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    // get damaged region
    Rectangle clipRect = g.getClipBounds();
    int clipx = clipRect.x;
    int clipy = clipRect.y;
    int clipw = clipRect.width;
    int cliph = clipRect.height;

    // fill damaged region only
    g.setColor(Color.white);//from  ww  w  .  ja va  2 s  . c  o  m
    g.fillRect(clipx, clipy, clipw, cliph);

    if (clipx <= 240 && clipy <= 240) {
        g.setColor(Color.yellow);
        g.fillOval(0, 0, 240, 240);
        System.out.println(" yellow Oval repainted.");
    }

    if (clipx + clipw >= 160 && clipx <= 400 && clipy + cliph >= 160 && clipy <= 400) {
        g.setColor(Color.magenta);
        g.fillOval(160, 160, 240, 240);
        System.out.println(" magenta Oval repainted.");
    }

    int iconWidth = java2sLogo.getIconWidth();
    int iconHeight = java2sLogo.getIconHeight();

    if (clipx + clipw >= 280 - (iconWidth / 2) && clipx <= (280 + (iconWidth / 2))
            && clipy + cliph >= 120 - (iconHeight / 2) && clipy <= (120 + (iconHeight / 2))) {
        java2sLogo.paintIcon(this, g, 280 - (iconWidth / 2), 120 - (iconHeight / 2));
        System.out.println(" logo below blue Rect repainted.");
    }

    if (clipx + clipw >= 120 - (iconWidth / 2) && clipx <= (120 + (iconWidth / 2))
            && clipy + cliph >= 280 - (iconHeight / 2) && clipy <= (280 + (iconHeight / 2))) {
        java2sLogo.paintIcon(this, g, 120 - (iconWidth / 2), 280 - (iconHeight / 2));
        System.out.println(" logo below red Rect repainted.");
    }

    if (clipx + clipw >= 60 && clipx <= 180 && clipy + cliph >= 220 && clipy <= 340) {
        g.setColor(red);
        g.fillRect(60, 220, 120, 120);
        System.out.println(" red Rect repainted.");

    }

    if (clipx + clipw > 140 && clipx < 260 && clipy + cliph > 140 && clipy < 260) {
        g.setColor(green);
        g.fillOval(140, 140, 120, 120);
        System.out.println(" green Oval repainted.");

    }

    if (clipx + clipw > 220 && clipx < 380 && clipy + cliph > 60 && clipy < 180) {
        g.setColor(blue);
        g.fillRect(220, 60, 120, 120);
        System.out.println(" blue Rect repainted.");
    }

    g.setColor(Color.black);

    g.setFont(monoFont);
    FontMetrics fm = g.getFontMetrics();
    iconWidth = fm.stringWidth("Java Source");
    iconHeight = fm.getAscent();
    int d = fm.getDescent();
    if (clipx + clipw > 120 - (iconWidth / 2) && clipx < (120 + (iconWidth / 2))
            && clipy + cliph > (120 + (iconHeight / 4)) - iconHeight && clipy < (120 + (iconHeight / 4)) + d) {
        g.drawString("Java Source", 120 - (iconWidth / 2), 120 + (iconHeight / 4));
        System.out.println(" Java Source repainted.");
    }

    g.setFont(sanFont);
    fm = g.getFontMetrics();
    iconWidth = fm.stringWidth("and");
    iconHeight = fm.getAscent();
    d = fm.getDescent();
    if (clipx + clipw > 200 - (iconWidth / 2) && clipx < (200 + (iconWidth / 2))
            && clipy + cliph > (200 + (iconHeight / 4)) - iconHeight && clipy < (200 + (iconHeight / 4)) + d) {
        g.drawString("and", 200 - (iconWidth / 2), 200 + (iconHeight / 4));
        System.out.println(" and repainted.");
    }

    g.setFont(serifFont);
    fm = g.getFontMetrics();
    iconWidth = fm.stringWidth("Support.");
    iconHeight = fm.getAscent();
    d = fm.getDescent();

    if (clipx + clipw > 280 - (iconWidth / 2) && clipx < (280 + (iconWidth / 2))
            && clipy + cliph > (280 + (iconHeight / 4)) - iconHeight && clipy < (280 + (iconHeight / 4)) + d) {
        g.drawString("Support.", 280 - (iconWidth / 2), 280 + (iconHeight / 4));
        System.out.println(" Support. repainted.");
    }
}

From source file:Main.java

/**
 * Prints a <code>Document</code> using a monospaced font, word wrapping on
 * the characters ' ', '\t', '\n', ',', '.', and ';'.  This method is
 * expected to be called from Printable 'print(Graphics g)' functions.
 *
 * @param g The graphics context to write to.
 * @param doc The <code>javax.swing.text.Document</code> to print.
 * @param fontSize the point size to use for the monospaced font.
 * @param pageIndex The page number to print.
 * @param pageFormat The format to print the page with.
 * @param tabSize The number of spaces to expand tabs to.
 *
 * @see #printDocumentMonospaced//from   w  w  w . j  ava2s .  c  om
 */
public static int printDocumentMonospacedWordWrap(Graphics g, Document doc, int fontSize, int pageIndex,
        PageFormat pageFormat, int tabSize) {

    g.setColor(Color.BLACK);
    g.setFont(new Font("Monospaced", Font.PLAIN, fontSize));

    // Initialize our static variables (these are used by our tab expander below).
    tabSizeInSpaces = tabSize;
    fm = g.getFontMetrics();

    // Create our tab expander.
    //RPrintTabExpander tabExpander = new RPrintTabExpander();

    // Get width and height of characters in this monospaced font.
    int fontWidth = fm.charWidth('w'); // Any character will do here, since font is monospaced.
    int fontHeight = fm.getHeight();

    int MAX_CHARS_PER_LINE = (int) pageFormat.getImageableWidth() / fontWidth;
    int MAX_LINES_PER_PAGE = (int) pageFormat.getImageableHeight() / fontHeight;

    final int STARTING_LINE_NUMBER = MAX_LINES_PER_PAGE * pageIndex;

    // The (x,y) coordinate to print at (in pixels, not characters).
    // Since y is the baseline of where we'll start printing (not the top-left
    // corner), we offset it by the font's ascent ( + 1 just for good measure).
    xOffset = (int) pageFormat.getImageableX();
    int y = (int) pageFormat.getImageableY() + fm.getAscent() + 1;

    // A counter to keep track of the number of lines that WOULD HAVE been
    // printed if we were printing all lines.
    int numPrintedLines = 0;

    // Keep going while there are more lines in the document.
    currentDocLineNumber = 0; // The line number of the document we're currently on.
    rootElement = doc.getDefaultRootElement(); // To shorten accesses in our loop.
    numDocLines = rootElement.getElementCount(); // The number of lines in our document.
    while (currentDocLineNumber < numDocLines) {

        // Get the line we are going to print.
        String curLineString;
        Element currentLine = rootElement.getElement(currentDocLineNumber);
        int startOffs = currentLine.getStartOffset();
        try {
            curLineString = doc.getText(startOffs, currentLine.getEndOffset() - startOffs);
        } catch (BadLocationException ble) { // Never happens
            ble.printStackTrace();
            return Printable.NO_SUCH_PAGE;
        }

        // Remove newlines, because they end up as boxes if you don't; this is a monospaced font.
        curLineString = curLineString.replaceAll("\n", "");

        // Replace tabs with how many spaces they should be.
        if (tabSizeInSpaces == 0) {
            curLineString = curLineString.replaceAll("\t", "");
        } else {
            int tabIndex = curLineString.indexOf('\t');
            while (tabIndex > -1) {
                int spacesNeeded = tabSizeInSpaces - (tabIndex % tabSizeInSpaces);
                String replacementString = "";
                for (int i = 0; i < spacesNeeded; i++)
                    replacementString += ' ';
                // Note that "\t" is actually a regex for this method.
                curLineString = curLineString.replaceFirst("\t", replacementString);
                tabIndex = curLineString.indexOf('\t');
            }
        }

        // If this document line is too long to fit on one printed line on the page,
        // break it up into multpile lines.
        while (curLineString.length() > MAX_CHARS_PER_LINE) {

            int breakPoint = getLineBreakPoint(curLineString, MAX_CHARS_PER_LINE) + 1;

            numPrintedLines++;
            if (numPrintedLines > STARTING_LINE_NUMBER) {
                g.drawString(curLineString.substring(0, breakPoint), xOffset, y);
                y += fontHeight;
                if (numPrintedLines == STARTING_LINE_NUMBER + MAX_LINES_PER_PAGE)
                    return Printable.PAGE_EXISTS;
            }

            curLineString = curLineString.substring(breakPoint, curLineString.length());

        }

        currentDocLineNumber += 1; // We have printed one more line from the document.

        numPrintedLines++;
        if (numPrintedLines > STARTING_LINE_NUMBER) {
            g.drawString(curLineString, xOffset, y);
            y += fontHeight;
            if (numPrintedLines == STARTING_LINE_NUMBER + MAX_LINES_PER_PAGE)
                return Printable.PAGE_EXISTS;
        }

    }

    // Now, the whole document has been "printed."  Decide if this page had any text on it or not.
    if (numPrintedLines > STARTING_LINE_NUMBER)
        return Printable.PAGE_EXISTS;
    return Printable.NO_SUCH_PAGE;

}

From source file:ded.ui.DiagramController.java

/** The core of the paint routine, after we decide whether to interpose
  * another buffer. *//* w  w w.j av  a  2  s . c  o  m*/
private void innerPaint(Graphics g) {
    super.paint(g);

    // I do not know the proper way to get a font set automatically
    // in a Graphics object.  Calling JComponent.setFont has gotten
    // me nowhere.  Setting it myself when I first get control
    // seems to work; but note that I have to do this *after*
    // calling super.paint().
    g.setFont(this.dedWindow.diagramFont);

    // Filename label.
    if (this.diagram.drawFileName && !this.fileName.isEmpty()) {
        String name = new File(this.fileName).getName();
        FontMetrics fm = g.getFontMetrics();
        LineMetrics lm = fm.getLineMetrics(name, g);
        int x = fileNameLabelMargin;
        int y = fileNameLabelMargin + (int) lm.getAscent();
        g.drawString(name, x, y);
        y += (int) lm.getUnderlineOffset() + 1 /*...*/;
        g.drawLine(x, y, x + fm.stringWidth(name), y);
    }

    // Controllers.
    for (Controller c : this.controllers) {
        if (c.isSelected()) {
            c.paintSelectionBackground(g);
        }
        c.paint(g);
    }

    // Lasso rectangle.
    if (this.mode == Mode.DCM_RECT_LASSO) {
        Rectangle r = this.getLassoRect();
        g.drawRect(r.x, r.y, r.width, r.height);
    }

    // Current focused Component.
    if (debugFocus) {
        KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        Component fo = kfm.getFocusOwner();
        g.drawString("Focus: " + fo, 3, this.getHeight() - 22);
    }

    // Mode label.
    if (this.mode != Mode.DCM_SELECT) {
        g.drawString("Mode: " + this.mode.description, 3, this.getHeight() - 4);
    } else if (this.fpsMeasurementMode) {
        this.fpsFrameCount++;
        long current = System.currentTimeMillis();
        long millis = current - this.fpsStartMillis;
        if (millis > 1000) {
            // Update the FPS measurement with the results for this
            // interval.
            this.fpsSampleCount++;
            this.fpsMeasurement = "FPS: " + this.fpsFrameCount + " (millis=" + millis + ", samples="
                    + this.fpsSampleCount + ")";

            // Reset the counters.
            this.fpsStartMillis = current;
            this.fpsFrameCount = 0;
        }
        g.drawString(this.fpsMeasurement + " (Ctrl+G to stop)", 3, this.getHeight() - 4);
    }
}