Example usage for java.awt Graphics setColor

List of usage examples for java.awt Graphics setColor

Introduction

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

Prototype

public abstract void setColor(Color c);

Source Link

Document

Sets this graphics context's current color to the specified color.

Usage

From source file:ded.ui.DiagramController.java

/** Check to see if the font is rendering properly.  I have had a
  * lot of trouble getting this to work on a wide range of
  * machines and JVMs.  If the font rendering does not work, just
  * alert the user to the problem but keep going. */
public void checkFontRendering() {
    // Render the glyph for 'A' in a box just large enough to
    // contain it when rendered properly.
    int width = 9;
    int height = 11;
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics g = bi.createGraphics();
    ColorModel colorModel = bi.getColorModel();

    g.setColor(Color.WHITE);
    g.fillRect(0, 0, width, height);// w w  w.ja  v a 2s .  c o  m

    g.setColor(Color.BLACK);
    g.setFont(this.dedWindow.diagramFont);
    g.drawString("A", 0, 10);

    // Print that glyph as a string.
    StringBuilder sb = new StringBuilder();
    for (int y = 0; y < height; y++) {
        int bits = 0;
        for (int x = 0; x < width; x++) {
            int pixel = bi.getRGB(x, y);
            int red = colorModel.getRed(pixel);
            int green = colorModel.getGreen(pixel);
            int blue = colorModel.getBlue(pixel);
            int alpha = colorModel.getAlpha(pixel);
            boolean isWhite = (red == 255 && green == 255 && blue == 255 && alpha == 255);
            boolean isBlack = (red == 0 && green == 0 && blue == 0 && alpha == 255);
            sb.append(
                    isWhite ? "_" : isBlack ? "X" : ("(" + red + "," + green + "," + blue + "," + alpha + ")"));

            bits <<= 1;
            if (!isWhite) {
                bits |= 1;
            }
        }
        sb.append(String.format("  (0x%03X)\n", bits));
    }

    // Also include some of the font metrics.
    FontMetrics fm = g.getFontMetrics();
    sb.append("fm: ascent=" + fm.getAscent() + " leading=" + fm.getLeading() + " charWidth('A')="
            + fm.charWidth('A') + " descent=" + fm.getDescent() + " height=" + fm.getHeight() + "\n");

    String actualGlyph = sb.toString();

    g.dispose();

    // The expected glyph and metrics.
    String expectedGlyph = "_________  (0x000)\n" + "____X____  (0x010)\n" + "___X_X___  (0x028)\n"
            + "___X_X___  (0x028)\n" + "__X___X__  (0x044)\n" + "__X___X__  (0x044)\n" + "__XXXXX__  (0x07C)\n"
            + "_X_____X_  (0x082)\n" + "_X_____X_  (0x082)\n" + "_X_____X_  (0x082)\n" + "_________  (0x000)\n"
            + "fm: ascent=10 leading=1 charWidth('A')=9 descent=3 height=14\n";

    if (!expectedGlyph.equals(actualGlyph)) {
        // Currently, this is known to happen when using OpenJDK 6
        // and 7, with 6 being close to right and 7 being very bad.
        // I also have reports of it happening on certain Mac OS/X
        // systems, but I haven't been able to determine what the
        // important factor there is.
        String warningMessage = "There is a problem with the font rendering.  The glyph "
                + "for the letter 'A' should look like:\n" + expectedGlyph + "but it renders as:\n"
                + actualGlyph + "\n" + "This probably means there is a bug in the TrueType "
                + "font library.  You might try a different Java version.  "
                + "(I'm working on how to solve this permanently.)";
        System.err.println(warningMessage);
        this.log(warningMessage);
        SwingUtil.errorMessageBox(null /*component*/, warningMessage);
    }
}

From source file:ala.soils2sat.DrawingUtils.java

public static Rectangle drawString(Graphics g, Font font, String text, int x, int y, int width, int height,
        int align, boolean wrap) {
    g.setFont(font);//from ww w .ja va 2  s .c  om
    FontMetrics fm = g.getFontMetrics(font);

    setPreferredAliasingMode(g);

    Rectangle ret = new Rectangle(0, 0, 0, 0);

    if (text == null) {
        return ret;
    }
    String[] alines = text.split("\\n");
    ArrayList<String> lines = new ArrayList<String>();
    for (String s : alines) {
        if (wrap && fm.stringWidth(s) > width) {
            // need to split this up into multiple lines...
            List<String> splitLines = wrapString(s, fm, width);
            lines.addAll(splitLines);
        } else {
            lines.add(s);
        }
    }
    int numlines = lines.size();
    while (fm.getHeight() * numlines > height) {
        numlines--;
    }
    if (numlines > 0) {
        int maxwidth = 0;
        int minxoffset = y + width;
        int totalheight = (numlines * fm.getHeight());

        int linestart = ((height / 2) - (totalheight / 2));

        if (!wrap) {
            ret.y = y + linestart;
        } else {
            ret.y = y;
            linestart = 0;
        }
        for (int idx = 0; idx < numlines; ++idx) {
            String line = lines.get(idx);
            int stringWidth = fm.stringWidth(line);
            // the width of the label depends on the font :
            // if the width of the label is larger than the item
            if (stringWidth > 0 && width < stringWidth) {
                // We have to truncate the label
                line = clipString(null, fm, line, width);
                stringWidth = fm.stringWidth(line);
            }

            int xoffset = 0;
            int yoffset = linestart + fm.getHeight() - fm.getDescent();
            if (align == TEXT_ALIGN_RIGHT) {
                xoffset = (width - stringWidth);
            } else if (align == TEXT_ALIGN_CENTER) {
                xoffset = (int) Math.round((double) (width - stringWidth) / (double) 2);
            }

            if (xoffset < minxoffset) {
                minxoffset = xoffset;
            }
            g.drawString(line, x + xoffset, y + yoffset);
            if (stringWidth > maxwidth) {
                maxwidth = stringWidth;
            }
            linestart += fm.getHeight();
        }

        ret.width = maxwidth;
        ret.height = totalheight;
        ret.x = x + minxoffset;

        // Debug only...
        if (DEBUG) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.setStroke(new BasicStroke(1));
            g.setColor(Color.blue);
            g.drawRect(ret.x, ret.y, ret.width, ret.height);
            g.setColor(Color.green);
            g.drawRect(x, y, width, height);
        }

        return ret;
    }
    return ret;
}

From source file:com.projity.contrib.calendar.JXXMonthView.java

/**
 * Paints the background of the month string. The bounding box for this
 * background can be modified by setting its insets via
 * setMonthStringInsets. The color of the background can be set via
 * setMonthStringBackground./*ww  w  .  ja v  a  2s. c o  m*/
 *
 * @see #setMonthStringBackground
 * @see #setMonthStringInsets
 * @param g
 *            Graphics object to paint to.
 * @param x
 *            x-coordinate of upper left corner.
 * @param y
 *            y-coordinate of upper left corner.
 * @param width
 *            width of the bounding box.
 * @param height
 *            height of the bounding box.
 */
protected void paintMonthStringBackground(Graphics g, int x, int y, int width, int height) {
    // Modify bounds by the month string insets.
    x = _ltr ? x + _monthStringInsets.left : x + _monthStringInsets.left;
    y = y + _monthStringInsets.top;
    width = width - _monthStringInsets.left - _monthStringInsets.right;
    height = height - _monthStringInsets.top - _monthStringInsets.bottom;

    g.setColor(_monthStringBackground);
    g.fillRect(x, y, width, height);
}

From source file:org.pmedv.blackboard.components.BoardEditor.java

@Override
protected void paintComponent(Graphics g) {
    Boolean useLayerColor = (Boolean) Preferences.values
            .get("org.pmedv.blackboard.BoardDesignerPerspective.useLayerColor");

    // clear all      
    // g.clearRect(0, 0, getWidth(), getHeight());
    g.setColor(BLANK);
    g.fillRect(0, 0, getWidth(), getHeight());
    // some nice anti aliasing...
    Graphics2D g2 = (Graphics2D) g;
    RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2.setRenderingHints(rh);/* ww  w  .  j a v  a2 s.  c  o  m*/

    // TODO : Should this be done here?
    // Sort layers by z-index

    g2.setColor(Color.LIGHT_GRAY);
    g2.setStroke(BoardUtil.stroke_1_0f);

    Collections.sort(model.getLayers());
    for (int i = model.getLayers().size() - 1; i >= 0; i--) {
        // Sort items by z-index
        Collections.sort(model.getLayers().get(i).getItems());
        drawLayer(model.getLayers().get(i), g2);
    }

    // draw selection border
    if (state.equals(SelectionState.DRAGGING_NEW_SELECTION) && button1Pressed) {
        g2.setColor(Color.GREEN);
        g2.setStroke(BoardUtil.stroke_1_0f);
        if (dragStopX < dragStartX && dragStopY > dragStartY) {
            selectionBorder.setSize(dragStartX - dragStopX, dragStopY - dragStartY);
            selectionBorder.setLocation(dragStopX, dragStartY);
        } else if (dragStopY < dragStartY && dragStopX > dragStartX) {
            selectionBorder.setSize(dragStopX - dragStartX, dragStartY - dragStopY);
            selectionBorder.setLocation(dragStartX, dragStopY);
        } else if (dragStopX < dragStartX && dragStopY < dragStartY) {
            selectionBorder.setSize(dragStartX - dragStopX, dragStartY - dragStopY);
            selectionBorder.setLocation(dragStopX, dragStopY);
        } else {
            selectionBorder.setSize(dragStopX - dragStartX, dragStopY - dragStartY);
            selectionBorder.setLocation(dragStartX, dragStartY);
        }
        g2.draw(selectionBorder);
    }
    // display shape currently being drawed
    if (lineStartX > 0 && lineStartY > 0 && lineStopX > 0 && lineStopY > 0) {

        if (useLayerColor)
            g2.setColor(model.getCurrentLayer().getColor());
        else
            g2.setColor(palette.getCurrentColor());

        g2.setStroke((BasicStroke) shapesPanel.getThicknessCombo().getSelectedItem());
        // draw new line
        if (editorMode.equals(EditorMode.DRAW_LINE)) {

            if (useLayerColor)
                currentDrawingLine.setColor(model.getCurrentLayer().getColor());
            else
                currentDrawingLine.setColor(palette.getCurrentColor());

            currentDrawingLine.setStartType((LineEdgeType) shapesPanel.getStartLineCombo().getSelectedItem());
            currentDrawingLine.setEndType((LineEdgeType) shapesPanel.getEndLineCombo().getSelectedItem());
            currentDrawingLine.setStroke((BasicStroke) shapesPanel.getThicknessCombo().getSelectedItem());
            currentDrawingLine.getStart().setLocation(lineStartX, lineStartY);
            currentDrawingLine.getEnd().setLocation(lineStopX, lineStopY);
            currentDrawingLine.draw(g2);
        } else if (editorMode.equals(EditorMode.DRAW_MEASURE)) {
            currentDrawingLine.setStroke(Measure.DEFAULT_STROKE);
            currentDrawingLine.getStart().setLocation(lineStartX, lineStartY);
            currentDrawingLine.getEnd().setLocation(lineStopX, lineStopY);
            currentDrawingLine.draw(g2);
        }
        // draw new box or ellipse
        else if (editorMode.equals(EditorMode.DRAW_RECTANGLE) || editorMode.equals(EditorMode.DRAW_ELLIPSE)) {
            int xLoc = lineStartX;
            int yLoc = lineStartY;
            int width = lineStopX - lineStartX;
            int height = lineStopY - lineStartY;
            ShapeStyle style = (ShapeStyle) shapesPanel.getStyleCombo().getSelectedItem();
            if (style == null || style.equals(ShapeStyle.FILLED)) {
                if (editorMode.equals(EditorMode.DRAW_RECTANGLE)) {
                    g2.fillRect(xLoc, yLoc, width, height);
                } else {
                    g2.fillOval(xLoc, yLoc, width, height);
                }
            } else if (style.equals(ShapeStyle.OUTLINED)) {
                g2.setStroke((BasicStroke) shapesPanel.getThicknessCombo().getSelectedItem());
                if (editorMode.equals(EditorMode.DRAW_RECTANGLE)) {
                    g2.drawRect(xLoc, yLoc, width, height);
                } else {
                    g2.drawOval(xLoc, yLoc, width, height);
                }
            }
        }
    }
    // draw selection handles
    if (selectedItem != null) {
        g2.setStroke(BoardUtil.stroke_1_0f);
        g2.setColor(Color.GREEN);
        selectedItem.drawHandles(g2, 8);
    }

    // draw border

    if (zoomLayer != null) {
        TransformUI ui = (TransformUI) (Object) zoomLayer.getUI();
        DefaultTransformModel xmodel = (DefaultTransformModel) ui.getModel();

        if (xmodel.isMirror()) {
            g2.setColor(Color.RED);
        } else {
            g2.setColor(Color.GREEN);
        }
    } else {
        g2.setColor(Color.GREEN);
    }

    g2.setStroke(DEFAULT_STROKE);

    Rectangle border = new Rectangle(0, 0, model.getWidth() - 1, model.getHeight() - 1);
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
    g2.draw(border);

    if (model.getType().equals(BoardType.STRIPES) || model.getType().equals(BoardType.HOLES)) {

        g2.setColor(Color.BLACK);
        g2.setFont(miniFont);

        int index = 1;

        for (int x = 12; x < model.getWidth() - 16; x += 16) {
            g2.drawString(String.valueOf(index++), x, 8);
        }

        index = 1;

        for (int y = 18; y < model.getHeight(); y += 16) {
            g2.drawString(String.valueOf(index++), 3, y);
        }

    }

    if (editorMode.equals(EditorMode.CHECK_CONNECTIONS)) {
        if (connectedLines != null) {
            for (Line line : connectedLines) {
                line.drawFat(g2);
            }
        }
    }

    if (drawing) {

        g2.setColor(Color.BLUE);
        g2.setStroke(DEFAULT_STROKE);

        if (selectedPin != null) {
            g2.drawRect(lineStopX - 8, lineStopY - 8, 16, 16);
        }

    }

    super.paintComponents(g2);
}

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

public void parse(InputFile inputFile, Format ext, int type, boolean thumbOnly) {
    int i = 0;//w  w  w  . ja  va2 s .  com

    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:com.headswilllol.basiclauncher.Launcher.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setFont(font);// w ww .  j a  va 2 s  . c o  m
    if (updateMsg != null) {
        g.drawString("Update Available!", centerText(g, "Update Available!"), 50);
        g.setFont(smallFont);
        g.drawString(updateMsg, centerText(g, updateMsg), 100);
    }

    else if (progress == null)
        g.drawString(NAME + " Launcher", centerText(g, NAME + " Launcher"), 50);

    else {
        g.drawString(progress, centerText(g, progress), height / 2);
        if (fail != null)
            g.drawString(fail, centerText(g, fail), height / 2 + 50);
        else {
            if (aSize != -1 && eSize != -1) {
                String s = (aSize * 8) + "/" + (int) (eSize * 8) + " B";
                if (eSize * 8 >= 1024)
                    if (eSize * 8 >= 1024 * 1024)
                        s = String.format("%.2f", aSize * 8 / 1024 / 1024) + "/"
                                + String.format("%.2f", eSize * 8 / 1024 / 1024) + " MiB";
                    else
                        s = String.format("%.2f", aSize * 8 / 1024) + "/"
                                + String.format("%.2f", eSize * 8 / 1024) + " KiB";
                g.drawString(s, centerText(g, s), height / 2 + 40);
                String sp = "@" + (int) speed + " B/s";
                if (speed >= 1024)
                    if (speed >= 1024 * 1024)
                        sp = "@" + String.format("%.2f", (speed / 1024 / 1024)) + " MiB/s";
                    else
                        sp = "@" + String.format("%.2f", (speed / 1024)) + " KiB/s";
                g.drawString(sp, centerText(g, sp), height / 2 + 80);
                int barWidth = 500;
                int barHeight = 35;
                g.setColor(Color.LIGHT_GRAY);
                g.drawRect(width / 2 - barWidth / 2, height / 2 + 100, barWidth, barHeight);
                g.setColor(Color.GREEN);
                g.fillRect(width / 2 - barWidth / 2 + 1, height / 2 + 100 + 1,
                        (int) ((aSize / eSize) * (double) barWidth - 2), barHeight - 1);
                g.setColor(new Color(.2f, .2f, .2f));
                int percent = (int) (aSize / (double) eSize * 100);
                g.drawString(percent + "%", centerText(g, percent + "%"), height / 2 + 128);
            }
        }
    }
}

From source file:com.projity.contrib.calendar.JXXMonthView.java

/**
 * {@inheritDoc}/*from   w w  w . jav a 2s.  com*/
 */
protected void paintComponent(Graphics g) {
    Object oldAAValue = null;
    Graphics2D g2 = (g instanceof Graphics2D) ? (Graphics2D) g : null;
    if (g2 != null && _antiAlias) {
        oldAAValue = g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    }

    Rectangle clip = g.getClipBounds();

    updateIfNecessary();

    if (isOpaque()) {
        g.setColor(getBackground());
        g.fillRect(clip.x, clip.y, clip.width, clip.height);
    }
    g.setColor(getForeground());
    Color shadowColor = g.getColor();
    shadowColor = new Color(shadowColor.getRed(), shadowColor.getGreen(), shadowColor.getBlue(),
            (int) (.20 * 255));

    FontMetrics fm = g.getFontMetrics();

    // Reset the calendar.
    _cal.setTimeInMillis(_firstDisplayedDate);

    // Center the calendars vertically in the available space.
    int y = _startY;
    for (int row = 0; row < _numCalRows; row++) {
        // Center the calendars horizontally in the available space.
        int x = _startX;
        int tmpX, tmpY;

        // Check if this row falls in the clip region.
        _bounds.x = 0;
        _bounds.y = _startY + row * (_calendarHeight + CALENDAR_SPACING);
        _bounds.width = getWidth();
        _bounds.height = _calendarHeight;

        if (!_bounds.intersects(clip)) {
            _cal.add(Calendar.MONTH, _numCalCols);
            y += _calendarHeight + CALENDAR_SPACING;
            continue;
        }

        for (int column = 0; column < _numCalCols; column++) {
            String monthName = _monthsOfTheYear[_cal.get(Calendar.MONTH)];
            monthName = monthName + " " + _cal.get(Calendar.YEAR);

            _bounds.x = _ltr ? x : x - _calendarWidth;
            _bounds.y = y + _boxPaddingY;
            _bounds.width = _calendarWidth;
            _bounds.height = _boxHeight;

            if (_bounds.intersects(clip)) {
                // Paint month name background.
                paintMonthStringBackground(g, _bounds.x, _bounds.y, _bounds.width, _bounds.height);

                // Paint month name.
                g.setColor(getForeground());
                tmpX = _ltr ? x + (_calendarWidth / 2) - (fm.stringWidth(monthName) / 2)
                        : x - (_calendarWidth / 2) - (fm.stringWidth(monthName) / 2) - 1;
                tmpY = y + _boxPaddingY + _boxHeight - fm.getDescent();

                g.drawString(monthName, tmpX, tmpY);

                if ((_dropShadowMask & MONTH_DROP_SHADOW) != 0) {
                    g.setColor(shadowColor);
                    g.drawString(monthName, tmpX + 1, tmpY + 1);
                    g.setColor(getForeground());
                }
            }

            _bounds.x = _ltr ? x : x - _calendarWidth;
            _bounds.y = y + _boxPaddingY + _boxHeight + _boxPaddingY + _boxPaddingY;
            _bounds.width = _calendarWidth;
            _bounds.height = _boxHeight;

            if (_bounds.intersects(clip)) {
                _cal.set(Calendar.DAY_OF_MONTH, _cal.getActualMinimum(Calendar.DAY_OF_MONTH));
                Calendar weekCal = (Calendar) _cal.clone();
                // Paint short representation of day of the week.
                int dayIndex = _firstDayOfWeek - 1;
                int month = weekCal.get(Calendar.MONTH);
                //               dayIndex = (_cal.get(Calendar.DAY_OF_WEEK) -1) %7;
                for (int i = 0; i < DAYS_IN_WEEK; i++) {
                    //                  PROJITY_MODIFICATION
                    // set the week calendar to the current day of week and make sure it's still in this month
                    weekCal.set(Calendar.DAY_OF_WEEK, dayIndex + 1);
                    if (weekCal.get(Calendar.MONTH) != month)
                        weekCal.roll(Calendar.DAY_OF_YEAR, 7); // make sure in this month

                    tmpX = _ltr
                            ? x + (i * (_boxPaddingX + _boxWidth + _boxPaddingX)) + _boxPaddingX
                                    + (_boxWidth / 2) - (fm.stringWidth(_daysOfTheWeek[dayIndex]) / 2)
                            : x - (i * (_boxPaddingX + _boxWidth + _boxPaddingX)) - _boxPaddingX
                                    - (_boxWidth / 2) - (fm.stringWidth(_daysOfTheWeek[dayIndex]) / 2);
                    tmpY = y + _boxPaddingY + _boxHeight + _boxPaddingY + _boxPaddingY + fm.getAscent();
                    boolean flagged = _flaggedWeekDates[dayIndex];
                    boolean colored = _coloredWeekDates[dayIndex];
                    calculateBoundsForDay(_bounds, weekCal, true);
                    drawDay(colored, flagged, false, g, _daysOfTheWeek[dayIndex], tmpX, tmpY);

                    //                  if ((_dropShadowMask & WEEK_DROP_SHADOW) != 0) {
                    //                     calculateBoundsForDay(_bounds,weekCal,true); // add shadow arg
                    //                     drawDay(colored,flagged,false,g,_daysOfTheWeek[dayIndex], tmpX + 1,
                    //                           tmpY + 1);
                    //                  }
                    if (_selectedWeekDays[dayIndex]) {
                        paintSelectedDayBackground(g, _bounds.x, _bounds.y, _bounds.width, _bounds.height);
                    }
                    dayIndex++;
                    if (dayIndex == 7) {
                        dayIndex = 0;
                    }
                }

                int lineOffset = 2;
                // Paint a line across bottom of days of the week.
                g.drawLine(_ltr ? x + 2 : x - 3, lineOffset + y + (_boxPaddingY * 3) + (_boxHeight * 2),
                        _ltr ? x + _calendarWidth - 3 : x - _calendarWidth + 2,
                        lineOffset + y + (_boxPaddingY * 3) + (_boxHeight * 2));
                if ((_dropShadowMask & MONTH_LINE_DROP_SHADOW) != 0) {
                    g.setColor(shadowColor);
                    g.drawLine(_ltr ? x + 3 : x - 2, y + (_boxPaddingY * 3) + (_boxHeight * 2) + 1,
                            _ltr ? x + _calendarWidth - 2 : x - _calendarWidth + 3,
                            y + (_boxPaddingY * 3) + (_boxHeight * 2) + 1);
                    g.setColor(getForeground());
                }
            }

            // Check if the month to paint falls in the clip.
            _bounds.x = _startX + (_ltr ? column * (_calendarWidth + CALENDAR_SPACING)
                    : -(column * (_calendarWidth + CALENDAR_SPACING) + _calendarWidth));
            _bounds.y = _startY + row * (_calendarHeight + CALENDAR_SPACING);
            _bounds.width = _calendarWidth;
            _bounds.height = _calendarHeight;

            // Paint the month if it intersects the clip. If we don't move
            // the calendar forward a month as it would have if paintMonth
            // was called.
            if (_bounds.intersects(clip)) {
                paintMonth(g, column, row);
            } else {
                _cal.add(Calendar.MONTH, 1);
            }

            x += _ltr ? _calendarWidth + CALENDAR_SPACING : -(_calendarWidth + CALENDAR_SPACING);
        }
        y += _calendarHeight + CALENDAR_SPACING;
    }

    // Restore the calendar.
    _cal.setTimeInMillis(_firstDisplayedDate);
    if (g2 != null && _antiAlias) {
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldAAValue);
    }
}

From source file:web.diva.server.model.SomClustering.SomClustImgGenerator.java

private void drawSquares(Graphics squares, Point start, Rectangle bounds, Dataset dataset,
        boolean clusterColumns) {
    //        ColorFactory colors = ColorFactoryList.getInstance().getActiveColorFactory(dataset);
    colors = colorFactory.getActiveColorFactory(dataset);
    Rectangle view = getSquaresBounds(dataset);
    squares.translate(start.x, start.y);
    int rows = this.countgenes(this.rowNode);
    int counter = 0;
    double[] gengenscalevals = null;
    int[] upperArrangement = null;
    if (clusterColumns) {
        upperArrangement = upperTree.arrangement;
    } else {/* ww w .ja  v a 2s . c  o  m*/
        upperArrangement = new int[dataset.getColumnIds().length];
        for (int x = 0; x < dataset.getColumnIds().length; x++)
            upperArrangement[x] = x;
    }
    double[][] dat = null;
    dat = dataset.getData();
    if (sideTree == null) {
        return;
    }
    for (int i = 0; i < sideTree.arrangement.length; i++) {
        double v = 0;
        Rectangle sqr = new Rectangle(0, 0, squareW, squareL);
        for (int j = 0; j < upperArrangement.length; j++) {
            if (bounds == null || bounds.intersects((j * squareW), (i * squareL), squareW, squareL)) {

                if (upperTree != null) {

                    sqr.setLocation((j * squareW), (i * squareL));
                    if (!view.intersects(sqr)) {
                        continue;
                    }

                    if (sideTree.arrangement[i] != -1 && upperArrangement[j] != -1) {

                        if (dataset.isMissing(sideTree.arrangement[i], upperArrangement[j])) {
                            squares.setColor(colors.getMissing());
                        } else {
                            if (!gengenscale) {
                                v = dat[sideTree.arrangement[i]][upperArrangement[j]];
                                squares.setColor(colors.getColor(v));
                            } else {
                                v = gengenscalevals[upperArrangement[j]];
                                squares.setColor(colors.getColor(v));
                            }
                        }
                        squares.fillRect((j * squareW), (i * squareL), squareW, squareL);
                    }
                } else {
                    sqr.setLocation((j * squareW), (i * squareL));
                    if (!view.intersects(sqr)) {
                        continue;
                    }

                    v = dat[sideTree.arrangement[i]][upperArrangement[j]];

                    if (dataset.isMissing(sideTree.arrangement[i], upperArrangement[j])) {
                        squares.setColor(colors.getMissing());
                    } else {
                        squares.setColor(colors.getColor(v));
                    }

                    squares.fillRect((j * squareW), (i * squareL), squareW, squareL);
                }
            }
        }
        counter++;
        if (counter == rows) {
            break;
        }
    }
    counter = 0;
    if (true) {
        squares.setColor(GridCol);
        for (int i = 0; i < sideTree.arrangement.length + 1; i++) {
            if (bounds == null
                    || bounds.intersects(0, i * squareL, upperArrangement.length * squareW, i * squareL)) {
                squares.drawLine(0, i * squareL, (upperArrangement.length * squareW) + 0, i * squareL);
            }
            counter++;
            if (counter > rows) {
                break;
            }
        }
        for (int j = 0; j < upperArrangement.length; j++) {
            if (bounds == null || bounds.intersects(j * squareW, 0, j * squareW, rows * squareL)) {
                squares.drawLine(j * squareW, 0, j * squareW, rows * squareL);
            }
        }

        if (bounds == null || bounds.intersects(upperArrangement.length * squareW, 0,
                upperArrangement.length * squareW, rows * squareL)) {
            squares.drawLine(upperArrangement.length * squareW, 0, upperArrangement.length * squareW,
                    rows * squareL);
        }

    }
    squares.translate(-start.x, -start.y);
}

From source file:display.ANNFileFilter.java

License:asdf

public void paintComponent(Graphics g) {
    int nValue = 500 / lValue;
    int x = 0;/* ww w . ja v  a2s  .co m*/
    int y = 0;

    int count = 0;
    for (int i = 0; i < (lValue * lValue); i++) {
        Color c = new Color(colorValues[i][0], colorValues[i][1], colorValues[i][2]);
        g.setColor(c);
        g.fillRect(x, y, nValue, nValue);
        x = x + nValue;
        if (count == (lValue - 1)) {
            x = 0;
            y = y + nValue;
            count = -1;
        }
        count++;

    }
}

From source file:com.jcraft.weirdx.DDXWindowImp.java

public final Graphics getGraphics(GC gc, int mask) {
    if (!isVisible()) {
        return null;
    }/*  w w  w .  jav  a 2 s. co m*/
    if (offg == null)
        allocImage();
    Graphics graphics = offg;
    if ((mask & GC.GCSubwindowMode) != 0 && (gc.attr & GC.IncludeInferiors) != 0) {
        graphics = getGraphics();
        window.currentGC = null;
    } else {
        if (gc == window.currentGC && gc.time == window.gctime && (mask & ~window.gmask) == 0) {
            //System.out.println("DDXWindow skip");
            return graphics;
        }
        window.gctime = gc.time;
        window.currentGC = gc;
        window.gmask = mask;
    }

    if (gc.clip_mask != null && gc.clip_mask instanceof ClipRectangles) {
        java.awt.Rectangle rec = (Rectangle) (gc.clip_mask.getMask());
        if (rec != null) {
            graphics = offg;
        }

        if (rec == null
                || (rec.x == 0 && rec.y == 0 && rec.width == window.width && rec.height == window.height)) {
            //   return graphics;
        } else {
            graphics.setClip(rec.x, rec.y, rec.width, rec.height);
        }
    }

    if ((mask & GC.GCFunction) != 0) {
        Color color = window.getColormap().getColor(gc.fgPixel);
        if (gc.function == GC.GXxor) {
            window.gmask &= ~GC.GCFunction;
            graphics.setXORMode(new Color((color.getRGB() ^ graphics.getColor().getRGB()) & 0xffffff));
        } else if (gc.function == GC.GXinvert) {
            window.gmask &= ~GC.GCFunction;
            graphics.setXORMode(window.screen.defaultColormap.getColor(window.background.pixel));
        } else {
            graphics.setColor(color);
        }
    }

    if ((mask & GC.GCFont) != 0) {
        XFont font = gc.font;
        graphics.setFont(font.getFont());
    }

    if ((mask & GC.GCLineWidth) != 0 || (mask & GC.GCLineStyle) != 0 || (mask & GC.GCCapStyle) != 0
            || (mask & GC.GCJoinStyle) != 0) {
    }
    return graphics;
}