Example usage for java.awt Graphics2D setBackground

List of usage examples for java.awt Graphics2D setBackground

Introduction

In this page you can find the example usage for java.awt Graphics2D setBackground.

Prototype

public abstract void setBackground(Color color);

Source Link

Document

Sets the background color for the Graphics2D context.

Usage

From source file:gdt.jgui.entity.webset.JWeblinkEditor.java

private void showIconMenu(MouseEvent e) {
    try {//w  ww .  ja  v a 2  s .co  m
        iconMenu = new JPopupMenu();
        JMenuItem loadItem = new JMenuItem("Load");
        iconMenu.add(loadItem);
        loadItem.setHorizontalTextPosition(JMenuItem.RIGHT);
        loadItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    String favicon$ = "http://www.google.com/s2/favicons?domain=" + addressField.getText();
                    URL url = new URL(favicon$);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    ImageIcon icon = new ImageIcon(ImageIO.read(input));
                    int type = BufferedImage.TYPE_INT_RGB;
                    BufferedImage out = new BufferedImage(24, 24, type);
                    Color background = JWeblinkEditor.this.getBackground();
                    Graphics2D g2 = out.createGraphics();
                    g2.setBackground(background);
                    g2.clearRect(0, 0, 24, 24);
                    Image image = icon.getImage();
                    g2.drawImage(image, 4, 4, null);
                    g2.dispose();
                    icon = new ImageIcon(out);
                    iconIcon.setIcon(icon);
                    input.close();
                } catch (Exception ee) {
                    Logger.getLogger(getClass().getName()).info(ee.toString());
                }
            }
        });
        JMenuItem setItem = new JMenuItem("Set");
        iconMenu.add(setItem);
        setItem.setHorizontalTextPosition(JMenuItem.RIGHT);
        setItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("WeblinkEditor:set icon");
                JIconSelector is = new JIconSelector();
                String isLocator$ = is.getLocator();
                if (entihome$ != null)
                    isLocator$ = Locator.append(isLocator$, Entigrator.ENTIHOME, entihome$);
                if (entityKey$ != null)
                    isLocator$ = Locator.append(isLocator$, EntityHandler.ENTITY_KEY, entityKey$);

                String responseLocator$ = getLocator();
                responseLocator$ = Locator.append(responseLocator$, JRequester.REQUESTER_ACTION,
                        ACTION_SET_ICON);
                responseLocator$ = Locator.append(responseLocator$, BaseHandler.HANDLER_METHOD, "response");
                isLocator$ = Locator.append(isLocator$, JRequester.REQUESTER_RESPONSE_LOCATOR,
                        Locator.compressText(responseLocator$));
                JConsoleHandler.execute(console, isLocator$);
            }
        });
        iconMenu.show(e.getComponent(), e.getX(), e.getY());
    } catch (Exception ee) {
        Logger.getLogger(getClass().getName()).severe(ee.toString());
    }
}

From source file:au.com.gaiaresources.bdrs.controller.test.TestDataCreator.java

private byte[] createImage(int width, int height, String text) throws IOException {
    if (width < 0) {
        width = random.nextInt(DEFAULT_MAX_IMAGE_WIDTH - DEFAULT_MIN_IMAGE_WIDTH) + DEFAULT_MIN_IMAGE_WIDTH;
    }//ww w .  ja  v  a 2  s.  c  om
    if (height < 0) {
        height = random.nextInt(DEFAULT_MAX_IMAGE_HEIGHT - DEFAULT_MIN_IMAGE_HEIGHT) + DEFAULT_MIN_IMAGE_HEIGHT;
    }

    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2 = (Graphics2D) img.getGraphics();
    g2.setBackground(new Color(220, 220, 220));

    Dimension size;
    float fontSize = g2.getFont().getSize();
    // Make the text as large as possible.
    do {
        g2.setFont(g2.getFont().deriveFont(fontSize));
        FontMetrics metrics = g2.getFontMetrics(g2.getFont());
        int hgt = metrics.getHeight();
        int adv = metrics.stringWidth(text);
        size = new Dimension(adv + 2, hgt + 2);
        fontSize = fontSize + 1f;
    } while (size.width < Math.round(0.9 * width) && size.height < Math.round(0.9 * height));

    g2.setColor(Color.DARK_GRAY);
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2.drawString(text, (width - size.width) / 2, (height - size.height) / 2);
    g2.setColor(Color.LIGHT_GRAY);
    g2.drawRect(0, 0, width - 1, height - 1);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(width * height);
    ImageIO.write(img, "png", baos);
    baos.flush();
    byte[] rawBytes = baos.toByteArray();
    baos.close();

    return rawBytes;
}

From source file:io.github.dsheirer.spectrum.SpectrumPanel.java

/**
 * Draws the current fft spectrum with a line and a gradient fill.
 *//*from www . j  a  va2s .c  o m*/
private void drawSpectrum(Graphics2D graphics) {
    Dimension size = getSize();

    //Draw the background
    Rectangle background = new Rectangle(0, 0, size.width, size.height);
    graphics.setColor(mColorSpectrumBackground);
    graphics.draw(background);
    graphics.fill(background);

    //Define the gradient
    GradientPaint gradient = new GradientPaint(0, (getSize().height - mSpectrumInset) / 2,
            mColorSpectrumGradientTop, 0, getSize().height, mColorSpectrumGradientBottom);

    graphics.setBackground(mColorSpectrumBackground);

    GeneralPath spectrumShape = new GeneralPath();

    //Start at the lower right inset point
    spectrumShape.moveTo(size.getWidth(), size.getHeight() - mSpectrumInset);

    //Draw to the lower left
    spectrumShape.lineTo(0, size.getHeight() - mSpectrumInset);

    float[] bins = getBins();

    //If we have FFT data to display ...
    if (bins != null) {
        float insideHeight = size.height - mSpectrumInset;

        float scalor = insideHeight / -mDBScale;

        /* Calculate based on bin size - 1, since bin 0 is rendered at zero
           * and the last bin is rendered at the width */
        float binSize = (float) size.width / ((float) (bins.length));

        for (int x = 0; x < bins.length; x++) {
            float height;

            height = bins[x] * scalor;

            if (height > insideHeight) {
                height = insideHeight;
            }

            if (height < 0) {
                height = 0;
            }

            float xAxis = (float) x * binSize;

            spectrumShape.lineTo(xAxis, height);
        }
    }
    //Otherwise show an empty spectrum
    else {
        //Draw Left Size
        graphics.setPaint(gradient);
        spectrumShape.lineTo(0, size.getHeight() - mSpectrumInset);
        //Draw Middle
        spectrumShape.lineTo(size.getWidth(), size.getHeight() - mSpectrumInset);
    }

    //Draw Right Side
    spectrumShape.lineTo(size.getWidth(), size.getHeight() - mSpectrumInset);

    graphics.setPaint(gradient);
    graphics.draw(spectrumShape);
    graphics.fill(spectrumShape);

    graphics.setPaint(mColorSpectrumLine);

    //Draw the bottom line under the spectrum
    graphics.draw(new Line2D.Float(0, size.height - mSpectrumInset, size.width, size.height - mSpectrumInset));
}

From source file:org.gumtree.vis.awt.CompositePanel.java

@Override
public BufferedImage getImage() {
    BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D gc2 = image.createGraphics();
    gc2.setBackground(Color.white);
    gc2.setPaint(Color.white);/*from   www . j  a  v  a 2 s  . c  o m*/
    gc2.fill(new Rectangle2D.Double(0, 0, getWidth(), getHeight()));
    for (IPlot plot : plotList) {
        if (plot instanceof JPanel) {
            JPanel panel = (JPanel) plot;
            Rectangle2D panelBounds = panel.getBounds();
            Image panelImage = plot.getImage();
            gc2.drawImage(panelImage, (int) panelBounds.getMinX(), (int) panelBounds.getMinY(), panel);
        }
    }
    gc2.dispose();
    return image;
}

From source file:au.com.gaiaresources.bdrs.controller.test.TestDataCreator.java

private byte[] getAndScaleImageData(int targetWidth, int targetHeight, File file) throws IOException {
    if (file == null) {
        return null;
    }/*from  ww w  . j a v  a 2s  .co m*/

    BufferedImage sourceImage = ImageIO.read(file);
    BufferedImage targetImage;
    if (targetWidth > -1 && targetHeight > -1) {
        // Resize the image as required to fit the space
        targetImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2_scaled = targetImage.createGraphics();
        // Better scaling
        g2_scaled.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BICUBIC);

        g2_scaled.setBackground(Color.WHITE);
        g2_scaled.clearRect(0, 0, targetWidth, targetHeight);

        int sourceWidth = sourceImage.getWidth();
        int sourceHeight = sourceImage.getHeight();

        double widthRatio = (double) targetWidth / (double) sourceWidth;
        double heightRatio = (double) targetHeight / (double) targetHeight;

        if (heightRatio > widthRatio) {
            int scaledHeight = (int) Math.round(widthRatio * sourceHeight);
            g2_scaled.drawImage(sourceImage, 0, (targetImage.getHeight() - scaledHeight) / 2,
                    targetImage.getWidth(), scaledHeight, g2_scaled.getBackground(), null);
        } else {
            int scaledWidth = (int) Math.round(heightRatio * sourceWidth);
            g2_scaled.drawImage(sourceImage, (targetImage.getWidth() - scaledWidth) / 2, 0, scaledWidth,
                    targetImage.getHeight(), new Color(0, 0, 0, 255), null);
        }
    } else {
        targetImage = sourceImage;
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream(targetWidth * targetHeight);
    ImageIO.write(targetImage, "png", baos);
    baos.flush();
    byte[] data = baos.toByteArray();
    baos.close();

    return data;
}

From source file:edu.umn.cs.spatialHadoop.operations.PyramidPlot.java

private static void plotLocal(Path inFile, Path outFile, OperationsParams params) throws IOException {
    int tileWidth = params.getInt("tilewidth", 256);
    int tileHeight = params.getInt("tileheight", 256);

    Color strokeColor = params.getColor("color", Color.BLACK);

    String hdfDataset = (String) params.get("dataset");
    Shape shape = hdfDataset != null ? new NASARectangle() : (Shape) params.getShape("shape", null);
    Shape plotRange = params.getShape("rect", null);

    String valueRangeStr = (String) params.get("valuerange");
    MinMax valueRange;//w  w  w  . j a  v  a 2 s  . c  o  m
    if (valueRangeStr == null) {
        valueRange = null;
    } else {
        String[] parts = valueRangeStr.split(",");
        valueRange = new MinMax(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
    }

    InputSplit[] splits;
    FileSystem inFs = inFile.getFileSystem(params);
    FileStatus inFStatus = inFs.getFileStatus(inFile);
    if (inFStatus != null && !inFStatus.isDir()) {
        // One file, retrieve it immediately.
        // This is useful if the input is a hidden file which is automatically
        // skipped by FileInputFormat. We need to plot a hidden file for the case
        // of plotting partition boundaries of a spatial index
        splits = new InputSplit[] { new FileSplit(inFile, 0, inFStatus.getLen(), new String[0]) };
    } else {
        JobConf job = new JobConf(params);
        ShapeInputFormat<Shape> inputFormat = new ShapeInputFormat<Shape>();
        ShapeInputFormat.addInputPath(job, inFile);
        splits = inputFormat.getSplits(job, 1);
    }

    boolean vflip = params.is("vflip");

    Rectangle fileMBR;
    if (plotRange != null) {
        fileMBR = plotRange.getMBR();
    } else if (hdfDataset != null) {
        // Plotting a NASA file
        fileMBR = new Rectangle(-180, -90, 180, 90);
    } else {
        fileMBR = FileMBR.fileMBR(inFile, params);
    }

    boolean keepAspectRatio = params.is("keep-ratio", true);
    if (keepAspectRatio) {
        // Adjust width and height to maintain aspect ratio
        if (fileMBR.getWidth() > fileMBR.getHeight()) {
            fileMBR.y1 -= (fileMBR.getWidth() - fileMBR.getHeight()) / 2;
            fileMBR.y2 = fileMBR.y1 + fileMBR.getWidth();
        } else {
            fileMBR.x1 -= (fileMBR.getHeight() - fileMBR.getWidth() / 2);
            fileMBR.x2 = fileMBR.x1 + fileMBR.getHeight();
        }
    }

    if (hdfDataset != null) {
        // Collects some stats about the HDF file
        if (valueRange == null)
            valueRange = Aggregate.aggregate(new Path[] { inFile }, params);
        NASAPoint.minValue = valueRange.minValue;
        NASAPoint.maxValue = valueRange.maxValue;
        NASAPoint.setColor1(params.getColor("color1", Color.BLUE));
        NASAPoint.setColor2(params.getColor("color2", Color.RED));
        NASAPoint.gradientType = params.getGradientType("gradient", NASAPoint.GradientType.GT_HUE);
    }

    boolean adaptiveSampling = params.getBoolean("sample", false);

    int numLevels = params.getInt("numlevels", 7);

    float[] levelProb = new float[numLevels];
    double[] scale2 = new double[numLevels];
    double[] scale = new double[numLevels];
    levelProb[0] = params.getFloat(GeometricPlot.AdaptiveSampleRatio, 0.1f);
    // Size of the whole file in pixels at the f

    scale2[0] = (double) tileWidth * tileHeight / (fileMBR.getWidth() * fileMBR.getHeight());
    scale[0] = Math.sqrt(scale2[0]);
    for (int level = 1; level < numLevels; level++) {
        levelProb[level] = levelProb[level - 1] * 4;
        scale2[level] = scale2[level - 1] * (1 << level) * (1 << level);
        scale[level] = scale[level - 1] * (1 << level);
    }

    Map<TileIndex, BufferedImage> tileImages = new HashMap<PyramidPlot.TileIndex, BufferedImage>();

    Map<TileIndex, Graphics2D> tileGraphics = new HashMap<PyramidPlot.TileIndex, Graphics2D>();

    GridInfo bottomGrid = new GridInfo(fileMBR.x1, fileMBR.y1, fileMBR.x2, fileMBR.y2);
    bottomGrid.rows = bottomGrid.columns = (int) Math.round(Math.pow(2, numLevels - 1));

    TileIndex tileIndex = new TileIndex();
    boolean gradualFade = !(shape instanceof Point) && params.getBoolean("fade", false);

    for (InputSplit split : splits) {
        ShapeRecordReader<Shape> reader = new ShapeRecordReader<Shape>(params, (FileSplit) split);
        Rectangle cell = reader.createKey();
        while (reader.next(cell, shape)) {
            Rectangle shapeMBR = shape.getMBR();
            if (shapeMBR != null) {
                int min_level = 0;

                if (adaptiveSampling) {
                    // Special handling for NASA data
                    double p = Math.random();
                    // Skip levels that do not satisfy the probability
                    while (min_level < numLevels && p > levelProb[min_level])
                        min_level++;
                }

                java.awt.Rectangle overlappingCells = bottomGrid.getOverlappingCells(shapeMBR);
                for (tileIndex.level = numLevels - 1; tileIndex.level >= min_level; tileIndex.level--) {
                    if (gradualFade && !(shape instanceof Point)) {
                        double areaInPixels = (shapeMBR.getWidth() + shapeMBR.getHeight())
                                * scale[tileIndex.level];
                        if (areaInPixels < 1.0 && Math.round(areaInPixels * 255) < 1.0) {
                            // This shape can be safely skipped as it is too small to be plotted
                            return;
                        }
                    }

                    for (int i = 0; i < overlappingCells.width; i++) {
                        tileIndex.x = i + overlappingCells.x;
                        for (int j = 0; j < overlappingCells.height; j++) {
                            tileIndex.y = j + overlappingCells.y;
                            // Draw in image associated with this tile
                            Graphics2D g;
                            {
                                g = tileGraphics.get(tileIndex);
                                if (g == null) {
                                    TileIndex key = tileIndex.clone();
                                    BufferedImage image = new BufferedImage(tileWidth, tileHeight,
                                            BufferedImage.TYPE_INT_ARGB);
                                    if (tileImages.put(key, image) != null)
                                        throw new RuntimeException(
                                                "Error! Image is already there but graphics is not "
                                                        + tileIndex);

                                    Color bg_color = new Color(0, 0, 0, 0);

                                    try {
                                        g = image.createGraphics();
                                    } catch (Throwable e) {
                                        g = new SimpleGraphics(image);
                                    }
                                    g.setBackground(bg_color);
                                    g.clearRect(0, 0, tileWidth, tileHeight);
                                    g.setColor(strokeColor);
                                    // Coordinates of this tile in image coordinates
                                    g.translate(-(tileWidth * tileIndex.x), -(tileHeight * tileIndex.y));

                                    tileGraphics.put(key, g);
                                }
                            }

                            shape.draw(g, fileMBR, tileWidth * (1 << tileIndex.level),
                                    tileHeight * (1 << tileIndex.level), scale2[tileIndex.level]);
                        }
                    }
                    // Shrink overlapping cells to match the upper level
                    int updatedX1 = overlappingCells.x / 2;
                    int updatedY1 = overlappingCells.y / 2;
                    int updatedX2 = (overlappingCells.x + overlappingCells.width - 1) / 2;
                    int updatedY2 = (overlappingCells.y + overlappingCells.height - 1) / 2;
                    overlappingCells.x = updatedX1;
                    overlappingCells.y = updatedY1;
                    overlappingCells.width = updatedX2 - updatedX1 + 1;
                    overlappingCells.height = updatedY2 - updatedY1 + 1;
                }
            }
        }
        reader.close();
    }
    // Write image to output
    for (Map.Entry<TileIndex, Graphics2D> tileGraph : tileGraphics.entrySet()) {
        tileGraph.getValue().dispose();
    }
    FileSystem outFS = outFile.getFileSystem(params);
    for (Map.Entry<TileIndex, BufferedImage> tileImage : tileImages.entrySet()) {
        tileIndex = tileImage.getKey();
        BufferedImage image = tileImage.getValue();
        if (vflip) {
            AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
            tx.translate(0, -image.getHeight());
            AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
            image = op.filter(image, null);
            tileIndex.y = ((1 << tileIndex.level) - 1) - tileIndex.y;
        }
        Path imagePath = new Path(outFile, tileIndex.getImageFileName());
        FSDataOutputStream outStream = outFS.create(imagePath);
        ImageIO.write(image, "png", outStream);
        outStream.close();
    }
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.reporting.AnnotationReportCanvas.java

public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
    if (pageIndex > 0) {
        return NO_SUCH_PAGE;
    } else {/*from   w w w .ja  v  a2  s  .  c  o m*/
        Graphics2D g2d = (Graphics2D) g;
        g2d.setBackground(Color.white);
        g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

        Dimension td = this.getPreferredSize();
        double sx = pageFormat.getImageableWidth() / td.width;
        double sy = pageFormat.getImageableHeight() / td.height;
        double s = Math.min(sx, sy);
        if (s < 1.)
            g2d.scale(s, s);

        RepaintManager.currentManager(this).setDoubleBufferingEnabled(false);
        this.paint(g2d);
        RepaintManager.currentManager(this).setDoubleBufferingEnabled(true);

        return PAGE_EXISTS;
    }
}

From source file:biogenesis.Organism.java

public BufferedImage getImage() {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = image.createGraphics();
    g.setBackground(Color.BLACK);
    g.clearRect(0, 0, width, height);//from  w ww.j  ava  2 s  .  com
    for (int i = _segments - 1; i >= 0; i--) {
        g.setColor(_segColor[i]);
        g.drawLine(x1[i] - x + _centerX, y1[i] - y + _centerY, x2[i] - x + _centerX, y2[i] - y + _centerY);
    }
    return image;
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.reporting.AnnotationReportCanvas.java

public BufferedImage getImage() {
    // Create an image that supports transparent pixels
    Dimension d = getPreferredSize();
    BufferedImage img = GraphicUtils.createCompatibleImage(d.width, d.height, false);

    // prepare graphics context
    Graphics2D g2d = img.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
    g2d.setBackground(new Color(255, 255, 255, 0));

    // paint/*from   w ww. j a v  a  2 s  .com*/
    is_printing = true;
    this.paint(g2d);
    is_printing = false;

    return img;
}