Example usage for java.awt RenderingHints KEY_ANTIALIASING

List of usage examples for java.awt RenderingHints KEY_ANTIALIASING

Introduction

In this page you can find the example usage for java.awt RenderingHints KEY_ANTIALIASING.

Prototype

Key KEY_ANTIALIASING

To view the source code for java.awt RenderingHints KEY_ANTIALIASING.

Click Source Link

Document

Antialiasing hint key.

Usage

From source file:SWT2D.java

private void run() {
    // Create top level shell
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Java 2D Example");
    // GridLayout for canvas and button
    shell.setLayout(new GridLayout());
    // Create container for AWT canvas
    final Composite canvasComp = new Composite(shell, SWT.EMBEDDED);
    // Set preferred size
    GridData data = new GridData();
    data.widthHint = 600;// w  w  w  .ja  v a  2 s.  c om
    data.heightHint = 500;
    canvasComp.setLayoutData(data);
    // Create AWT Frame for Canvas
    java.awt.Frame canvasFrame = SWT_AWT.new_Frame(canvasComp);
    // Create Canvas and add it to the Frame
    final java.awt.Canvas canvas = new java.awt.Canvas();
    canvasFrame.add(canvas);
    // Get graphical context and cast to Java2D
    final java.awt.Graphics2D g2d = (java.awt.Graphics2D) canvas.getGraphics();
    // Enable antialiasing
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    // Remember initial transform
    final java.awt.geom.AffineTransform origTransform = g2d.getTransform();
    // Create Clear button and position it
    Button clearButton = new Button(shell, SWT.PUSH);
    clearButton.setText("Clear");
    data = new GridData();
    data.horizontalAlignment = GridData.CENTER;
    clearButton.setLayoutData(data);
    // Event processing for Clear button
    clearButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            // Delete word list and redraw canvas
            wordList.clear();
            canvasComp.redraw();
        }
    });
    // Process canvas mouse clicks
    canvas.addMouseListener(new java.awt.event.MouseListener() {
        public void mouseClicked(java.awt.event.MouseEvent e) {
        }

        public void mouseEntered(java.awt.event.MouseEvent e) {
        }

        public void mouseExited(java.awt.event.MouseEvent e) {
        }

        public void mousePressed(java.awt.event.MouseEvent e) {
            // Manage pop-up editor
            display.syncExec(new Runnable() {
                public void run() {
                    if (eShell == null) {
                        // Create new Shell: non-modal!
                        eShell = new Shell(shell, SWT.NO_TRIM | SWT.MODELESS);
                        eShell.setLayout(new FillLayout());
                        // Text input field
                        eText = new Text(eShell, SWT.BORDER);
                        eText.setText("Text rotation in the SWT?");
                        eShell.pack();
                        // Set position (Display coordinates)
                        java.awt.Rectangle bounds = canvas.getBounds();
                        org.eclipse.swt.graphics.Point pos = canvasComp.toDisplay(bounds.width / 2,
                                bounds.height / 2);
                        Point size = eShell.getSize();
                        eShell.setBounds(pos.x, pos.y, size.x, size.y);
                        // Open Shell
                        eShell.open();
                    } else if (!eShell.isVisible()) {
                        // Editor versteckt, sichtbar machen
                        eShell.setVisible(true);
                    } else {
                        // Editor is visible - get text
                        String t = eText.getText();
                        // set editor invisible
                        eShell.setVisible(false);
                        // Add text to list and redraw canvas
                        wordList.add(t);
                        canvasComp.redraw();
                    }
                }
            });
        }

        public void mouseReleased(java.awt.event.MouseEvent e) {
        }
    });
    // Redraw the canvas
    canvasComp.addPaintListener(new PaintListener() {
        public void paintControl(PaintEvent e) {
            // Pass the redraw task to AWT event queue
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    // Compute canvas center
                    java.awt.Rectangle bounds = canvas.getBounds();
                    int originX = bounds.width / 2;
                    int originY = bounds.height / 2;
                    // Reset canvas
                    g2d.setTransform(origTransform);
                    g2d.setColor(java.awt.Color.WHITE);
                    g2d.fillRect(0, 0, bounds.width, bounds.height);
                    // Set font
                    g2d.setFont(new java.awt.Font("Myriad", java.awt.Font.PLAIN, 32));
                    double angle = 0d;
                    // Prepare star shape
                    double increment = Math.toRadians(30);
                    Iterator iter = wordList.iterator();
                    while (iter.hasNext()) {
                        // Determine text colors in RGB color cycle
                        float red = (float) (0.5 + 0.5 * Math.sin(angle));
                        float green = (float) (0.5 + 0.5 * Math.sin(angle + Math.toRadians(120)));
                        float blue = (float) (0.5 + 0.5 * Math.sin(angle + Math.toRadians(240)));
                        g2d.setColor(new java.awt.Color(red, green, blue));
                        // Redraw text
                        String text = (String) iter.next();
                        g2d.drawString(text, originX + 50, originY);
                        // Rotate for next text output
                        g2d.rotate(increment, originX, originY);
                        angle += increment;
                    }
                }
            });
        }
    });
    // Finish shell and open it
    shell.pack();
    shell.open();
    // SWT event processing
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:TextLayoutWithCarets.java

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);

    if (mInitialized == false)
        initialize(g2);/*from  www. j av a  2s  .c  o  m*/

    float x = 20, y = 80;
    mLayout.draw(g2, x, y);

    // Create a plain stroke and a dashed stroke.
    Stroke[] caretStrokes = new Stroke[2];
    caretStrokes[0] = new BasicStroke();
    caretStrokes[1] = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 0, new float[] { 4, 4 },
            0);

    // Now draw the carets
    Shape[] carets = mLayout.getCaretShapes(mHit.getInsertionIndex());
    for (int i = 0; i < carets.length; i++) {
        if (carets[i] != null) {
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            Shape shape = at.createTransformedShape(carets[i]);
            g2.setStroke(caretStrokes[i]);
            g2.draw(shape);
        }
    }
}

From source file:savant.amino.AminoCanvas.java

@Override
public void paintComponent(Graphics g) {
    if (GenomeUtils.getGenome().isSequenceSet()) {

        double aminoWidth = track.transformXPos(3) - track.transformXPos(0);
        if (aminoWidth > 0.5) {

            Graphics2D g2 = (Graphics2D) g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // We'll be drawing labels if a 'W' (tryptophan) will fit into the space of 3 bases.
            g2.setFont(g2.getFont().deriveFont(Font.PLAIN, 8));
            boolean labelled = g2.getFontMetrics().charWidth('W') < aminoWidth;

            try {
                List<Record> records = track.getDataInRange();
                if (records != null) {
                    for (Record r : records) {
                        RichIntervalRecord rr = (RichIntervalRecord) r;
                        int recordStart = rr.getInterval().getStart();
                        thickStart = rr.getThickStart();
                        int thickEnd = rr.getThickEnd() + 1;
                        LOG.debug(rr.getAlternateName() + ": thickStart=" + thickStart + ", thickEnd="
                                + thickEnd);

                        if (thickEnd > thickStart) {
                            sequence = GenomeUtils.getGenome().getSequence(
                                    NavigationUtils.getCurrentReferenceName(),
                                    RangeUtils.createRange(thickStart, thickEnd));

                            int pos = thickStart;
                            int leftovers = -1; // Left-overs from the previous block.
                            List<Block> blocks = rr.getBlocks();
                            if (blocks != null) {
                                for (Block b : blocks) {

                                    if (pos + 3 <= thickEnd) {
                                        // Block positions are relative to the start of the record.
                                        int blockStart = b.getPosition() + recordStart;
                                        int blockEnd = b.getEnd() + recordStart;
                                        LOG.debug(rr.getAlternateName() + ": blockStart=" + blockStart
                                                + ", blockEnd=" + blockEnd);

                                        AminoAcid a;

                                        // If we have leftovers, take care of them first.
                                        switch (leftovers) {
                                        case -1:
                                            // Fresh record with no leftovers.
                                            break;
                                        case 0:
                                            // No leftovers, so we can start immediately on the new block.
                                            pos = blockStart;
                                            if (pos < thickStart) {
                                                pos = thickStart;
                                            }
                                            break;
                                        case 1:
                                            // One base from previous block, two bases from current one.
                                            LOG.debug(rr.getAlternateName() + ": handling leftover "
                                                    + getBase(pos) + " at " + pos);
                                            if (rr.getStrand() == Strand.FORWARD) {
                                                a = AminoAcid.lookup(getBase(pos), getBase(blockStart),
                                                        getBase(blockStart + 1));
                                            } else {
                                                a = AminoAcid.lookup(getComplement(blockStart + 1),
                                                        getComplement(blockStart), getComplement(pos));
                                            }
                                            paintAminoAcid(g2, a, pos, 1, pos, labelled);
                                            paintAminoAcid(g2, a, blockStart, 2, blockStart - 1, labelled);
                                            pos = blockStart + 2;
                                            break;
                                        case 2:
                                            // Two bases from previous block, one base from current one.
                                            LOG.debug(rr.getAlternateName() + ": handling leftover "
                                                    + getBase(pos) + "," + getBase(pos + 1) + " at " + pos + ","
                                                    + (pos + 1));
                                            if (rr.getStrand() == Strand.FORWARD) {
                                                a = AminoAcid.lookup(getBase(pos), getBase(pos + 1),
                                                        getBase(blockStart));
                                            } else {
                                                a = AminoAcid.lookup(getComplement(blockStart),
                                                        getComplement(pos + 1), getComplement(pos));
                                            }
                                            paintAminoAcid(g2, a, pos, 2, pos, labelled);
                                            paintAminoAcid(g2, a, blockStart, 1, blockStart - 2, labelled);
                                            pos = blockStart + 1;
                                            break;
                                        }

                                        // Now, handle codons which are entirely contained within the block.
                                        while (pos + 3 <= blockEnd && pos + 3 <= thickEnd) {
                                            if (rr.getStrand() == Strand.FORWARD) {
                                                a = AminoAcid.lookup(getBase(pos), getBase(pos + 1),
                                                        getBase(pos + 2));
                                            } else {
                                                a = AminoAcid.lookup(getComplement(pos + 2),
                                                        getComplement(pos + 1), getComplement(pos));
                                            }
                                            paintAminoAcid(g2, a, pos, 3, pos, labelled);
                                            pos += 3;
                                        }
                                        leftovers = (blockEnd - pos) % 3;
                                        LOG.debug(rr.getAlternateName() + ": breaking out of loop: pos=" + pos
                                                + ", blockEnd=" + blockEnd + ", leftovers=" + leftovers);
                                    }//from   w  w w. ja  va  2s  .  co m
                                }
                            }
                        }
                    }
                }
            } catch (Exception x) {
                LOG.info("Unable to retrieve sequence.", x);
            }
        }
    }
}

From source file:components.SizeDisplayer.java

protected void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g.create(); //copy g
    Dimension minSize = getMinimumSize();
    Dimension prefSize = getPreferredSize();
    Dimension size = getSize();//from   w ww.ja  v a 2 s.c om
    int prefX = 0, prefY = 0;

    //Set hints so text looks nice.
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    //Draw the maximum size rectangle if we're opaque.
    if (isOpaque()) {
        g2d.setColor(getBackground());
        g2d.fillRect(0, 0, size.width, size.height);
    }

    //Draw the icon.
    if (icon != null) {
        Composite oldComposite = g2d.getComposite();
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f));
        icon.paintIcon(this, g2d, (size.width - icon.getIconWidth()) / 2,
                (size.height - icon.getIconHeight()) / 2);
        g2d.setComposite(oldComposite);
    }

    //Draw the preferred size rectangle.
    prefX = (size.width - prefSize.width) / 2;
    prefY = (size.height - prefSize.height) / 2;
    g2d.setColor(Color.RED);
    g2d.drawRect(prefX, prefY, prefSize.width - 1, prefSize.height - 1);

    //Draw the minimum size rectangle.
    if (minSize.width != prefSize.width || minSize.height != prefSize.height) {
        int minX = (size.width - minSize.width) / 2;
        int minY = (size.height - minSize.height) / 2;
        g2d.setColor(Color.CYAN);
        g2d.drawRect(minX, minY, minSize.width - 1, minSize.height - 1);
    }

    //Draw the text.
    if (text != null) {
        Dimension textSize = getTextSize(g2d);
        g2d.setColor(getForeground());
        g2d.drawString(text, (size.width - textSize.width) / 2,
                (size.height - textSize.height) / 2 + g2d.getFontMetrics().getAscent());
    }
    g2d.dispose();
}

From source file:peakmlviewer.dialog.PCADialog.java

public PCADialog(MainWnd mainwnd, Shell parent, String title) {
    super(parent, SWT.NONE);

    // save the parent pointer
    this.title = title;
    this.parent = parent;

    this.mainwnd = mainwnd;

    // create the window and set its properties
    shell = new Shell(parent, SWT.EMBEDDED | SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
    shell.setSize(500, 300);//from w  w w.  j  a v a2 s . co m
    shell.setText(title);

    // create the jfreechart
    plot = new XYPlot(collection, new NumberAxis("principal component 1"),
            new NumberAxis("principal component 2"), new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES));
    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainGridlinesVisible(true);
    plot.setRangeGridlinesVisible(true);
    plot.getRenderer().setBaseItemLabelsVisible(true);
    plot.getRenderer().setBaseItemLabelGenerator(new XYItemLabelGenerator() {
        public String generateLabel(XYDataset dataset, int series, int item) {
            return labels[item];
        }
    });

    chart = new JFreeChart("Principle Component Analysis", plot);
    chart.removeLegend();
    chart.setBackgroundPaint(Color.WHITE);
    chart.getRenderingHints().put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // add the components
    // --------------------------------------------------------------------------------
    // This uses the SWT-trick for embedding awt-controls in an SWT-Composit.
    try {
        System.setProperty("sun.awt.noerasebackground", "true");
    } catch (NoSuchMethodError error) {
        ;
    }

    java.awt.Frame frame = org.eclipse.swt.awt.SWT_AWT.new_Frame(shell);

    // create a new ChartPanel, without the popup-menu (5x false)
    frame.add(new ChartPanel(chart, false, false, false, false, false));
    // --------------------------------------------------------------------------------
}

From source file:org.jfree.chart.demo.FastScatterPlotDemo.java

/**
 * Creates a new fast scatter plot demo.
 *
 * @param title  the frame title.// w  w w.  ja  va 2 s  . com
 */
public FastScatterPlotDemo(final String title) {

    super(title);
    populateData();
    final NumberAxis domainAxis = new NumberAxis("X");
    domainAxis.setAutoRangeIncludesZero(false);
    final NumberAxis rangeAxis = new NumberAxis("Y");
    rangeAxis.setAutoRangeIncludesZero(false);
    final FastScatterPlot plot = new FastScatterPlot(this.data, domainAxis, rangeAxis);
    final JFreeChart chart = new JFreeChart("Fast Scatter Plot", plot);
    //        chart.setLegend(null);

    // force aliasing of the rendered content..
    chart.getRenderingHints().put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    final ChartPanel panel = new ChartPanel(chart, true);
    panel.setPreferredSize(new java.awt.Dimension(500, 270));
    //      panel.setHorizontalZoom(true);
    //    panel.setVerticalZoom(true);
    panel.setMinimumDrawHeight(10);
    panel.setMaximumDrawHeight(2000);
    panel.setMinimumDrawWidth(20);
    panel.setMaximumDrawWidth(2000);

    setContentPane(panel);

}

From source file:no.met.jtimeseries.chart.XYWindArrowRenderer.java

/**
 * Creates a new renderer./*from   w ww. j  a  v a2 s  . com*/
 */
public XYWindArrowRenderer() {
    super();
    renderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    renderHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
}

From source file:test.FastScatterDemo.java

/**
 * Creates a new fast scatter plot demo.
 *
 * @param title  the frame title./*from www  .j av a 2 s .  c  om*/
 */
public FastScatterDemo(final String title) {

    super(title);
    populateData();
    final NumberAxis domainAxis = new NumberAxis("X");
    domainAxis.setAutoRangeIncludesZero(false);
    final NumberAxis rangeAxis = new NumberAxis("Y");
    rangeAxis.setAutoRangeIncludesZero(false);
    final FastScatterPlot plot = new FastScatterPlot(this.data, domainAxis, rangeAxis);
    final JFreeChart chart = new JFreeChart("Fast Scatter Plot", plot);
    //        chart.setLegend(null);

    // force aliasing of the rendered content..
    chart.getRenderingHints().put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    final ChartPanel panel = new ChartPanel(chart, true);
    panel.setPreferredSize(new java.awt.Dimension(500, 270));
    //      panel.setHorizontalZoom(true);
    //    panel.setVerticalZoom(true);
    panel.setMinimumDrawHeight(10);
    panel.setMaximumDrawHeight(2000);
    panel.setMinimumDrawWidth(20);
    panel.setMaximumDrawWidth(2000);

    setContentPane(panel);

}

From source file:org.aludratest.cloud.selenium.SeleniumResourceBean.java

private byte[] takeSeleniumResourceScreenshot(String seleniumUrl) {
    String url = seleniumUrl;//from w  w w  .  j  a  v a2 s.  com
    url += "/selenium-server/driver/?cmd=captureScreenshotToString";

    InputStream in = null;
    try {
        in = new URL(url).openStream();
        in.read(new byte[3]); // read away "OK,"
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(in, baos);

        // decode Base64
        byte[] rawImageData = Base64.decodeBase64(baos.toByteArray());

        // create image from bytes
        BufferedImage img = ImageIO.read(new ByteArrayInputStream(rawImageData));

        // shrink image
        float sizeFactor = 2;
        BufferedImage imgSmall = new BufferedImage((int) (img.getWidth() / sizeFactor),
                (int) (img.getHeight() / sizeFactor), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = imgSmall.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.drawImage(img, 0, 0, imgSmall.getWidth(), imgSmall.getHeight(), 0, 0, img.getWidth(),
                img.getHeight(), null);
        g2d.dispose();

        // get PNG bytes
        baos = new ByteArrayOutputStream();
        ImageIO.write(imgSmall, "png", baos);
        return baos.toByteArray();
    } catch (IOException e) {
        LOG.warn("Could not take Selenium screenshot: " + e.getMessage());
        return null;
    } finally {
        IOUtils.closeQuietly(in);
    }
}

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;/*from  w  ww. ja 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();
}