Example usage for java.awt Graphics2D setPaint

List of usage examples for java.awt Graphics2D setPaint

Introduction

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

Prototype

public abstract void setPaint(Paint paint);

Source Link

Document

Sets the Paint attribute for the Graphics2D context.

Usage

From source file:ShapeMover.java

public void update(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    Dimension dim = getSize();/*from  ww w .j  ava2s.c o m*/
    int w = (int) dim.getWidth();
    int h = (int) dim.getHeight();
    g2.setStroke(new BasicStroke(8.0f));

    if (isFirstTime) {
        area = new Rectangle(dim);
        rect.setLocation(w / 2 - 50, h / 2 - 25);
        isFirstTime = false;
    }

    // Clears the rectangle that was previously drawn.
    g2.setPaint(Color.white);
    g2.fillRect(0, 0, w, h);

    g2.setColor(Color.red);
    g2.draw(rect);
    g2.setColor(Color.black);
    g2.fill(rect);
}

From source file:org.openfaces.component.chart.impl.renderers.LineFillRenderer.java

private void drawPrimaryLine(Graphics2D g2, Collection<Line2D> lines, int row, int item) {
    g2.setPaint(getItemPaint(row, item));
    g2.setStroke(getItemStroke(row, item));

    for (Line2D line : lines) {
        g2.draw(line);//  www  . j  a  v  a  2 s.c  o  m
    }
}

From source file:PaintSample.java

/**
 * Fills the component with the current Paint.
 *
 * @param g  the graphics device.//ww  w. j  a v  a  2s  .c o  m
 */
public void paintComponent(final Graphics g) {

    final Graphics2D g2 = (Graphics2D) g;
    final Dimension size = getSize();
    final Insets insets = getInsets();
    final double xx = insets.left;
    final double yy = insets.top;
    final double ww = size.getWidth() - insets.left - insets.right - 1;
    final double hh = size.getHeight() - insets.top - insets.bottom - 1;
    final Rectangle2D area = new Rectangle2D.Double(xx, yy, ww, hh);
    g2.setPaint(this.paint);
    g2.fill(area);
    g2.setPaint(Color.black);
    g2.draw(area);

}

From source file:Bouncer.java

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    setAntialiasing(g2);//from w  w  w  .  j  a va  2 s . c o  m
    setClip(g2);
    setTransform(g2);
    Shape shape = createShape();
    setPaint(g2);

    g2.fill(shape);

    if (mOutline) {
        setStroke(g2);
        g2.setPaint(Color.blue);
        g2.draw(shape);
    }
    drawAxes(g2);
}

From source file:com.stanley.captioner.Transcriber.java

public void start() {
    // Create stream speech recognizer.
    StreamSpeechRecognizer recognizer = null;
    try {/*from   ww  w .  j a v a2 s  . c  om*/
        recognizer = new StreamSpeechRecognizer(config);
    } catch (IOException e) {
        System.out.println("Failed to create recognizer.");
    }

    // Open print writer for writing text output.
    PrintWriter writer = null;
    try {
        writer = new PrintWriter(textOut);
    } catch (FileNotFoundException e) {
        System.out.println("Failed to create print writer.");
    }

    // Open stream for first pass.
    InputStream stream = null;
    try {
        stream = new FileInputStream(audio);
    } catch (FileNotFoundException e) {
        System.out.println("Failed to stream file.");
    }

    // Initialize loop variables.
    SpeechResult result;
    int resultCount = 0;
    Stats stats = recognizer.createStats(1);

    // Start recognizer for first pass.
    recognizer.startRecognition(stream);
    System.out.println("First pass (stats collection) started.");

    // First pass loop to collect statistics for model adaptation.
    while ((result = recognizer.getResult()) != null) {
        try {
            stats.collect(result);
        } catch (Exception e) {
            System.out.println("Failed to collect stats.");
        }

        resultCount++;

        // Toggle for testing.
        if (quickTest && resultCount > 5) {
            break;
        }
    }
    // Close recognizer (end of first pass).
    recognizer.stopRecognition();
    System.out.println("Stats collection stopped.");

    // Transform model using model adaptation.
    Transform transform = stats.createTransform();
    recognizer.setTransform(transform);

    // Reopen stream for second pass.
    stream = null;
    try {
        stream = new FileInputStream(audio);
    } catch (FileNotFoundException e) {
        System.out.println("Failed to stream file.");
    }

    // Start recognizer for second pass.
    recognizer.startRecognition(stream);
    System.out.println("Second pass started.");

    // Create output text file header.
    writer.printf("%-20s", "WORD:");
    writer.printf("%20s", "CONFIDENCE:");
    writer.printf("%20s", "START TIME:");
    writer.printf("%20s", "END_TIME:");
    writer.println();
    for (int i = 0; i < 80; i++) {
        writer.print("-");
    }
    writer.println();

    // Initialize loop variables.
    int wordCount = 0;
    String sentence = "";
    int sentenceLength = 0;
    long sentenceStart = 0;
    long sentenceEnd = 0;
    ArrayList<Sentence> sentences = new ArrayList<>();

    // Second pass loop to calculate sentences.
    RECOG: while ((result = recognizer.getResult()) != null) {
        for (WordResult wordResult : result.getWords()) {
            wordCount++;
            String word = wordResult.getWord().toString();
            double confidence = wordResult.getConfidence();
            long startTime = wordResult.getTimeFrame().getStart();
            long endTime = wordResult.getTimeFrame().getEnd();
            writer.printf("%-20s", word);
            writer.printf("%20.1f", confidence);
            writer.printf("%20d", startTime);
            writer.printf("%20d", endTime);
            writer.println();

            if (sentenceLength + word.length() < 40) {
                // Add to current sentence.
                sentence += " " + word;
                sentenceLength += word.length();
                sentenceEnd = endTime;
            } else {
                // End of current sentence, store and start a new one.
                sentences.add(new Sentence(sentence, sentenceStart, sentenceEnd));
                sentenceStart = sentenceEnd;
                sentence = "";
                sentenceLength = 0;
            }

            // Toggle for testing.
            if (quickTest && wordCount > 50) {
                break RECOG;
            }
        }
    }

    // Close print writer and recognizer (end of second pass).
    writer.close();
    recognizer.stopRecognition();
    System.out.println("Second pass stopped.");

    // Create folder for caption images.
    String imageDirPath = FilenameUtils.concat(textOut.getParent(),
            FilenameUtils.getBaseName(textOut.getAbsolutePath()));
    System.out.println(imageDirPath);
    File imageDir = new File(imageDirPath);
    if (!imageDir.exists()) {
        // Create the folder if it doesn't already exist.
        imageDir.mkdir();
    }

    // Calculate video output path.
    String videoOutPath = FilenameUtils.concat(textOut.getParent(),
            FilenameUtils.getBaseName(textOut.getAbsolutePath()) + ".mp4");
    System.out.println(videoOutPath);

    // Initialize a command string for overlaying the captions.
    String commandString = String.format("%s -y -loglevel quiet -i %s", new Converter().getFFmpegPath(),
            videoIn.getAbsolutePath());
    System.out.println(commandString);

    // Initialize a complex filter for overlaying the captions.
    String filterString = "-filter_complex";

    // Acquire a probe object for collecting video details.
    Converter converter = new Converter();
    FFprobe ffprobe = null;
    try {
        ffprobe = new FFprobe(converter.getFFprobePath());
    } catch (IOException e) {
        System.out.println("Failed to find ffprobe.");
    }

    // Probe the video for details.
    FFmpegProbeResult probeResult = null;
    try {
        probeResult = ffprobe.probe(videoIn.getAbsolutePath());
    } catch (IOException e) {
        System.out.println("Failed to probe video file.");
    }

    // Get the width and height of the video.
    FFmpegStream videoStream = probeResult.getStreams().get(0);
    int videoWidth = videoStream.width;
    int videoHeight = videoStream.height;

    // Calculate the x and y coordinates of the captions.
    int captionX = (videoWidth / 2) - 220;
    int captionY = videoHeight - 25 - 10;

    // Loop over the sentences, generate captions, and build command string.
    int k = 0;
    for (Sentence s : sentences) {
        // Create caption image from sentence.
        BufferedImage bi = new BufferedImage(440, 50, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = bi.createGraphics();
        g.setPaint(new Color(0, 0, 0, 128));
        g.fillRect(0, 0, 440, 50);
        g.setPaint(new Color(255, 255, 255, 255));
        g.setFont(new Font("Serif", Font.BOLD, 20));
        FontMetrics fm = g.getFontMetrics();
        int x = bi.getWidth() - fm.stringWidth(s.text) - 5;
        int y = fm.getHeight() - 5;
        g.drawString(s.text, x, y);
        g.dispose();

        // Write the image to file for future reference.
        String suffix = String.format("caption-%03d.png", k);
        String imagePath = FilenameUtils.concat(imageDirPath, suffix);
        try {
            File imageFile = new File(imagePath);
            ImageIO.write(bi, "png", imageFile);
        } catch (IOException e) {
            System.out.println("Failed to write caption image to file.");
        }

        // Add the caption image path to the command string.
        commandString += " -i " + imagePath;

        // Add an entry to the complex filter with the caption timeframe.
        if (k == 0) {
            filterString += String.format(" \"[0:v][1:v] overlay=%d:%d:enable='between(t,%d,%d)'%s", captionX,
                    captionY, s.startTime / 1000, s.endTime / 1000,
                    (k == sentences.size() - 1) ? "\"" : " [tmp];");
        } else {
            filterString += String.format(" [tmp][%d:v] overlay=%d:%d:enable='between(t,%d,%d)'%s", k + 1,
                    captionX, captionY, s.startTime / 1000, s.endTime / 1000,
                    (k == sentences.size() - 1) ? "\"" : " [tmp];");
        }
        k++;
    }

    // Build final command string.
    String finalCommand = String.format("%s %s -codec:a copy %s", commandString, filterString, videoOutPath);

    System.out.println(finalCommand);

    // Attempt to run the final command string to embed the captions.
    try {
        Process p = Runtime.getRuntime().exec(finalCommand);
        try {
            if (p.waitFor() != 0) {
                // Embedding the captions failed.
                System.out.println("Image overlay failed.");
            }
        } catch (InterruptedException e) {
            // Embedding the captions was interrupted.
            System.out.println("Interrupted image overlay.");
        }
    } catch (IOException e) {
        // Command string failed to execute.
        System.out.println("Failed to execute image overlay.");
    }

    // Delete intermediate audio file.
    audio.delete();

    System.out.println("........................CAPTIONING COMPLETE........................");
}

From source file:Main.java

@Override
protected void paintThumb(Graphics g, JComponent c, Rectangle r) {
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    Color color = null;//ww w . j a  v  a 2 s  . c  om
    JScrollBar sb = (JScrollBar) c;
    if (!sb.isEnabled() || r.width > r.height) {
        return;
    } else if (isDragging) {
        color = Color.DARK_GRAY;
    } else if (isThumbRollover()) {
        color = Color.LIGHT_GRAY;
    } else {
        color = Color.GRAY;
    }
    g2.setPaint(color);
    g2.fillRoundRect(r.x, r.y, r.width, r.height, 10, 10);
    g2.setPaint(Color.WHITE);
    g2.drawRoundRect(r.x, r.y, r.width, r.height, 10, 10);
    g2.dispose();
}

From source file:edu.jhuapl.graphs.jfreechart.CategoryGraphBarPainter.java

@Override
public void paintBar(Graphics2D g2, BarRenderer renderer, int row, int column, RectangularShape bar,
        RectangleEdge base) {//from w  w w . j a v  a2 s. c  o  m
    Paint itemPaint = itemProperty.get(row, column, Paint.class, renderer.getItemPaint(row, column),
            GraphSource.ITEM_COLOR);
    GradientPaintTransformer t = renderer.getGradientPaintTransformer();

    if (t != null && itemPaint instanceof GradientPaint) {
        itemPaint = t.transform((GradientPaint) itemPaint, bar);
    }

    g2.setPaint(itemPaint);
    g2.fill(bar);

    // draw the outline
    if (renderer.isDrawBarOutline()) {
        Stroke stroke = renderer.getItemOutlineStroke(row, column);
        Paint paint = renderer.getItemOutlinePaint(row, column);

        if (stroke != null && paint != null) {
            g2.setStroke(stroke);
            g2.setPaint(paint);
            g2.draw(bar);
        }
    }
}

From source file:com.rapidminer.gui.new_plotter.engine.jfreechart.legend.CustomLegendGraphic.java

@Override
public void draw(Graphics2D g2, Rectangle2D area) {

    area = trimMargin(area);//from w w  w  .  j a v  a2 s  .  com
    drawBorder(g2, area);
    area = trimBorder(area);
    area = trimPadding(area);

    if (isLineVisible()) {
        Point2D location = RectangleAnchor.coordinates(area, getShapeLocation());
        Shape aLine = ShapeUtilities.createTranslatedShape(getLine(), getShapeAnchor(), location.getX(),
                location.getY());
        g2.setPaint(getLinePaint());
        g2.setStroke(getLineStroke());
        g2.draw(aLine);
    }

    if (isShapeVisible()) {
        Point2D location = RectangleAnchor.coordinates(area, getShapeLocation());

        Shape s = ShapeUtilities.createTranslatedShape(getShape(), getShapeAnchor(), location.getX(),
                location.getY());
        if (isShapeFilled()) {
            Paint p = getFillPaint();
            if (p instanceof GradientPaint) {
                GradientPaint gp = (GradientPaint) getFillPaint();
                p = getFillPaintTransformer().transform(gp, s);
            } else if (p instanceof LinearGradientPaint) {
                LinearGradientPaint gradient = (LinearGradientPaint) p;
                Rectangle2D bounds = s.getBounds2D();
                p = getTranslatedLinearGradientPaint(gradient,
                        new Point2D.Double(bounds.getMinX(), bounds.getMinY()),
                        new Point2D.Double(bounds.getMaxX(), bounds.getMaxY()), false);
            }
            g2.setPaint(p);
            g2.fill(s);
        }
        if (isShapeOutlineVisible()) {
            g2.setPaint(getOutlinePaint());
            g2.setStroke(getOutlineStroke());
            g2.draw(s);
        }
    }

}

From source file:org.dishevelled.brainstorm.BrainStorm.java

/** {@inheritDoc} */
public void paintComponent(final Graphics graphics) {
    Graphics2D g = (Graphics2D) graphics;
    Paint oldPaint = g.getPaint();
    g.setPaint(backgroundColor);
    g.fill(getBounds());// w w w.j a  v  a 2  s  .c  om
    g.setPaint(oldPaint);
}

From source file:ShowOff.java

protected void drawBackground(Graphics2D g2) {
    int side = 45;
    int width = getSize().width;
    int height = getSize().height;
    Color[] colors = { Color.yellow, Color.cyan, Color.orange, Color.pink, Color.magenta, Color.lightGray };
    for (int y = 0; y < height; y += side) {
        for (int x = 0; x < width; x += side) {
            Ellipse2D ellipse = new Ellipse2D.Float(x, y, side, side);
            int index = (x + y) / side % colors.length;
            g2.setPaint(colors[index]);
            g2.fill(ellipse);/*  w  w w  .  ja  va  2 s  .co  m*/
        }
    }
}