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:info.debatty.java.datasets.examples.GaussianMixtureBuilder.java

/**
 * Creates a new fast scatter plot demo.
 *
 * @param title  the frame title.//  w  ww  .  ja va  2s .c om
 */
FastScatterPlot2D(final String title, final float[][] data) {

    super(title);
    final NumberAxis x_axis = new NumberAxis("X");
    x_axis.setAutoRangeIncludesZero(false);
    final NumberAxis y_axis = new NumberAxis("Y");
    y_axis.setAutoRangeIncludesZero(false);

    final FastScatterPlot plot = new FastScatterPlot(data, x_axis, y_axis);
    final JFreeChart chart = new JFreeChart(title, plot);

    // 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(1024, 768));

    setContentPane(panel);
}

From source file:com.sdk.connector.chart.CoherenceDomainRenderer.java

public CoherenceDomainRenderer(final String title, JPanel panel, String side) {
    sdf = Protocol.getInstance().getTimestampFormat();

    serieFFT.setKey(side + " FFT Based");
    serieLomb.setKey(side + " Lomb Based");
    serieMemse.setKey(side + " AR Based");

    dataset.addSeries(serieFFT);/*from   ww w  . j  av a 2s. c o  m*/
    dataset.addSeries(serieLomb);
    dataset.addSeries(serieMemse);

    chart = ChartFactory.createTimeSeriesChart(title,
            java.util.ResourceBundle.getBundle("com/sdk/connector/chart/Bundle").getString("coherence.xlabel"),
            java.util.ResourceBundle.getBundle("com/sdk/connector/chart/Bundle").getString("coherence.ylabel"),
            dataset, true, true, false);

    chart.getRenderingHints().put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    chart.getRenderingHints().put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    chart.getRenderingHints().put(RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    chart.getRenderingHints().put(RenderingHints.KEY_FRACTIONALMETRICS,
            RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    chart.getRenderingHints().put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    chart.getRenderingHints().put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
    chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    chart.getRenderingHints().put(RenderingHints.KEY_TEXT_LCD_CONTRAST, 100);
    //chart.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 0, 1000, Color.GREEN));
    // chart.setBackgroundPaint(new Color(220,255,220,0));
    //chart.setBackgroundImage(new javax.swing.ImageIcon(getClass().getResource("/com/sdk/connector/resources/background.png")).getImage());
    chart.addSubtitle(rangeAnnotation);
    plot = (XYPlot) chart.getPlot();

    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    renderer.setSeriesLinesVisible(0, true);
    renderer.setSeriesShapesVisible(0, true);
    renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator(
            StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT, sdf, new DecimalFormat("0.00")));
    renderer.setSeriesOutlinePaint(0, Color.BLACK);

    if (side.startsWith(
            java.util.ResourceBundle.getBundle("com/sdk/connector/chart/Bundle").getString("side.left"))) {
        renderer.setSeriesPaint(0, Color.BLUE);
        leftSide = true;
    } else {
        renderer.setSeriesPaint(0, Color.RED);
        leftSide = false;
    }
    renderer.setSeriesShape(0, new Ellipse2D.Double(-1.0, -1.0, 3.0, 3.0));

    DateTickUnit dtUnit = new DateTickUnit(DateTickUnitType.MINUTE, 1, tickSDF);
    final DateAxis domainAxis = (DateAxis) plot.getDomainAxis();
    domainAxis.setTickUnit(dtUnit);

    //        ValueAxis axis = plot.getDomainAxis();
    //        axis = plot.getRangeAxis();
    //        ((NumberAxis) axis).setTickUnit(new NumberTickUnit(100));

    plot.setRenderer(renderer);
    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainGridlinePaint(Color.BLACK);
    plot.setRangeGridlinePaint(Color.BLACK);
    plot.getRenderer().setSeriesStroke(0, new BasicStroke(1.0f));
    // plot.getRenderer().setSeriesStroke(1, new BasicStroke(1.0f));
    plot.setForegroundAlpha(0.5f);
    plot.setNoDataMessage(
            java.util.ResourceBundle.getBundle("com/sdk/connector/chart/Bundle").getString("message.wait"));
    plot.setRangePannable(true);
    plot.setDomainPannable(true);
    Color color1 = new Color(0, 0, 0, 24);
    Color color2 = new Color(255, 255, 255, 24);

    GradientPaint gp = new GradientPaint(0, 0, color1, 0, 0, color2);
    plot.setBackgroundPaint(gp);

    chartPanel = new ChartPanel(chart);

    panel.setLayout(new GridLayout(0, 1));

    panel.add(chartPanel);
    panel.repaint();
    panel.revalidate();

}

From source file:TapTapTap.java

@Override
public void paint(Graphics g, JComponent c) {
    int w = c.getWidth();
    int h = c.getHeight();

    // Paint the view.
    super.paint(g, c);

    if (!mIsRunning) {
        return;//from  w  ww.j a  va2 s  .  c  o  m
    }

    Graphics2D g2 = (Graphics2D) g.create();

    float fade = (float) mFadeCount / (float) mFadeLimit;
    // Gray it out.
    Composite urComposite = g2.getComposite();
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f * fade));
    g2.fillRect(0, 0, w, h);
    g2.setComposite(urComposite);

    // Paint the wait indicator.
    int s = Math.min(w, h) / 5;
    int cx = w / 2;
    int cy = h / 2;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setStroke(new BasicStroke(s / 4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
    g2.setPaint(Color.white);
    g2.rotate(Math.PI * mAngle / 180, cx, cy);
    for (int i = 0; i < 12; i++) {
        float scale = (11.0f - (float) i) / 11.0f;
        g2.drawLine(cx + s, cy, cx + s * 2, cy);
        g2.rotate(-Math.PI / 6, cx, cy);
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, scale * fade));
    }

    g2.dispose();
}

From source file:fr.ign.cogit.geoxygene.appli.layer.LayerViewAwtPanel.java

@Override
public final void paintComponent(final Graphics g) {
    try {/*from w w w  . j  a  v  a  2  s .c  om*/
        ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // // super.paintComponent(g);
        // // clear the graphics
        g.setColor(this.getBackground());
        g.fillRect(0, 0, this.getWidth(), this.getHeight());
        // copy the result of the rendering manager to the panel
        this.getRenderingManager().copyTo((Graphics2D) g);
        // if currently editing geometry
        this.paintGeometryEdition(g);
        this.paintOverlays(g);
        //
        if (this.recording) {
            this.saveImage();
        }
    } catch (Throwable t) {
        LayerViewAwtPanel.logger.error(I18N.getString("LayerViewAwtPanel.PaintError")); //$NON-NLS-1$
        t.printStackTrace();
        // TODO HANDLE EXCEPTIONS
    }
}

From source file:net.sf.firemox.clickable.target.card.VirtualCard.java

@SuppressWarnings("null")
@Override/* w w  w  . j  a  va2s.c  om*/
public void paintComponent(Graphics g) {
    final Graphics2D g2D = (Graphics2D) g;

    // Renderer
    g2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    // Optimization card painting
    final MZone container = card.getContainer();
    final boolean shortPaint = container == null || !container.isMustBePainted(card);

    // tap/reverse operation : PI/2, PI, -PI/2 rotation
    if (!shortPaint) {
        if (container.isMustBePaintedReversed(card)) {
            if (card.tapped) {
                g2D.translate(rotateTransformY, CardFactory.cardWidth + rotateTransformX);
                g2D.rotate(angle - Math.PI / 2);
            } else {
                g2D.translate(CardFactory.cardWidth + rotateTransformX,
                        CardFactory.cardHeight + rotateTransformY);
                g2D.rotate(Math.PI - angle);
            }
        } else {
            if (card.tapped) {
                g2D.translate(CardFactory.cardHeight + rotateTransformY, rotateTransformX);
                g2D.rotate(Math.PI / 2 + angle);
            } else {
                g2D.translate(rotateTransformX, rotateTransformY);
                g2D.rotate(angle);
            }
        }
    }

    if (container != null) {
        if (container.isVisibleForOpponent() && !card.isVisibleForOpponent() && card.isVisibleForYou()) {
            /*
             * This card is visible for you but not for opponent in despite of the
             * fact the container is public.
             */
            g2D.drawImage(card.scaledImage(), null, null);
            g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
            g2D.drawImage(DatabaseFactory.scaledBackImage, null, null);
        } else if (!card.isVisibleForYou()) {
            g2D.drawImage(DatabaseFactory.scaledBackImage, null, null);
        } else {
            g2D.drawImage(card.scaledImage(), null, null);
        }
    }

    if (shortPaint)
        return;

    /*
     * The card picture is displayed as a rounded rectangle with 0,90,180 or
     * 270
     */
    if (card.isHighLighted && (card.isVisibleForYou() || StackManager.idHandedPlayer == 0)) {
        // Draw the rounded colored rectangle
        g2D.setColor(card.highLightColor);
        g2D.draw3DRect(0, 0, CardFactory.cardWidth - 2, CardFactory.cardHeight - 2, false);
    }

    // Draw the eventual progress bar
    card.database.updatePaintNotification(card, g);

    // Cursor for our pretty pictures
    int px = 3;
    int py = 3;
    int maxX = CardFactory.cardWidth - 2;

    // for in-play, visible cards
    if (card.isVisibleForYou() || (container != null && container.isVisibleForYou())) {

        // draw registers above the card's picture
        if (refreshToolTipFilter().powerANDtoughness) {
            // power / toughness
            final String powerANDtoughness = String.valueOf(card.getValue(IdTokens.POWER)) + "/"
                    + card.getValue(IdTokens.TOUGHNESS);
            g2D.setFont(g2D.getFont().deriveFont(Font.BOLD, 13));
            final Rectangle2D stringDim = g2D.getFontMetrics().getStringBounds(powerANDtoughness, g2D);
            g2D.setColor(CardFactory.powerToughnessColor);
            g2D.drawString(powerANDtoughness, (int) (CardFactory.cardWidth - stringDim.getWidth() - 3),
                    CardFactory.cardHeight - 5);
            g2D.setColor(Color.BLUE);
            g2D.drawString(powerANDtoughness, (int) (CardFactory.cardWidth - stringDim.getWidth() - 3),
                    CardFactory.cardHeight - 6);
        }

        /*
         * START drawing additional pictures
         */

        // draw state pictures
        for (StatePicture statePicture : CardFactory.statePictures) {
            if (px + 13 > maxX) {
                px = 3;
                py += 13;
            }
            if (statePicture.paint(card, g2D, px, py)) {
                px += 13;
            }
        }

        // draw properties
        if (card.cachedProperties != null) {
            for (Integer property : card.cachedProperties) {
                if (Configuration.getBoolean("card.property.picture", true)
                        && CardFactory.propertyPictures.get(property) != null) {
                    // There is an associated picture to this property
                    if (px + 13 > maxX) {
                        px = 3;
                        py += 13;
                    }
                    g2D.drawImage(CardFactory.propertyPictures.get(property), px, py, 12, 12, null);
                    px += 13;
                }
            }
        }
    }

    // draw attached objects
    int startX = 3;
    int startY = CardFactory.cardHeight - 18;
    if (card.registerModifiers != null) {
        for (int i = card.registerModifiers.length; i-- > 0;) {
            if (card.registerModifiers[i] != null) {
                startX = card.registerModifiers[i].paintObject(g, startX, startY);
            }
        }
    }
    if (card.propertyModifier != null) {
        startX = card.propertyModifier.paintObject(g, startX, startY);
    }
    if (card.idCardModifier != null) {
        card.idCardModifier.paintObject(g, startX, startY);
        /*
         * END drawing additional pictures
         */
    }

    // Draw the target Id if helper said it
    final String id = TargetHelper.getInstance().getMyId(card);
    if (id != null) {
        if (px + 13 > maxX) {
            px = 3;
            py += 13;
        }
        if (id == TargetHelper.STR_CONTEXT1) {
            // TODO I am in the context 1, draw a picture
            g2D.setColor(Color.BLUE);
            g2D.setFont(g2D.getFont().deriveFont(Font.BOLD, 60 / id.length()));
            g2D.drawString(id, 5, CardFactory.cardHeight - 15);
        } else if (id == TargetHelper.STR_CONTEXT2) {
            // TODO I am in the context 2, draw a picture
            g2D.setColor(Color.BLUE);
            g2D.setFont(g2D.getFont().deriveFont(Font.BOLD, 60 / id.length()));
            g2D.drawString(id, 5, CardFactory.cardHeight - 15);
        } else if (id != TargetHelper.STR_SOURCE) {
            // } else if (id == TargetHelper.STR_SOURCE) {
            // TODO I am the source, draw a picture
            // } else {
            // I am a target
            g2D.drawImage(TargetHelper.getInstance().getTargetPictureSml(), px, py, null);
            py += 12;
        }
    }

    g2D.dispose();
}

From source file:org.jax.haplotype.analysis.visualization.SimplePhylogenyTreeImageFactory.java

/**
 * {@inheritDoc}//  www  . ja  v a2 s.  c  om
 */
public BufferedImage createPhylogenyImage(PhylogenyTreeNode phylogenyTree, int imageWidth, int imageHeight) {
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Creating phylogeny image for: "
                + phylogenyTree.resolveToSingleStrainLeafNodes(0.0).toNewickFormat());
    }

    BufferedImage bi = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D graphics = bi.createGraphics();
    graphics.setStroke(LINE_STROKE);
    graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphics.setColor(Color.BLACK);

    this.paintPhylogenyTree(graphics, phylogenyTree, imageWidth, imageHeight);

    return bi;
}

From source file:com.neophob.sematrix.generator.Textwriter.java

/**
 * create image.//from  w ww.  j  a v  a  2  s .c om
 *
 * @param text the text
 */
public void createTextImage(String text) {
    //only load if needed
    if (StringUtils.equals(text, this.text)) {
        return;
    }

    this.text = text;

    BufferedImage img = new BufferedImage(TEXT_BUFFER_X_SIZE, internalBufferYSize, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2 = img.createGraphics();
    FontRenderContext frc = g2.getFontRenderContext();
    TextLayout layout = new TextLayout(text, font, frc);
    Rectangle2D rect = layout.getBounds();

    int h = (int) (0.5f + rect.getHeight());
    maxXPos = (int) (0.5f + rect.getWidth()) + 5;
    ypos = internalBufferYSize - (internalBufferYSize - h) / 2;

    img = new BufferedImage(maxXPos, internalBufferYSize, BufferedImage.TYPE_INT_RGB);
    g2 = img.createGraphics();

    g2.setColor(color);
    g2.setFont(font);
    g2.setClip(0, 0, maxXPos, internalBufferYSize);
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);

    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2.drawString(text, xpos, ypos);
    DataBufferInt dbi = (DataBufferInt) img.getRaster().getDataBuffer();
    textBuffer = dbi.getData();
    g2.dispose();

    wait = 0;
    xofs = 0;
    scrollRight = false;
}

From source file:business.model.CaptchaModel.java

/**
 *
 * @param CaptchaText//  ww  w  .  j a  va2 s  . co m
 * @return
 */
public static BufferedImage CreateCaptchaImageOld(String CaptchaText) {
    BufferedImage localBufferedImage = new BufferedImage(width, height, 1);
    try {
        Graphics2D localGraphics2D = localBufferedImage.createGraphics();
        //        List<Font> fonts = FontFactory.getListFont();
        List<Font> fonts = new ArrayList<Font>();
        if (fonts.isEmpty()) {
            fonts.add(new Font("Nimbus Roman No9 L", 1, 30));
            fonts.add(new Font("VN-NTime", 1, 30));
            fonts.add(new Font("DT-Times", 1, 30));
            fonts.add(new Font("Times New Roman", 1, 30));
            fonts.add(new Font("Vni-Book123", 1, 30));
            fonts.add(new Font("VNI-Centur", 1, 30));
            fonts.add(new Font("DT-Brookly", 1, 30));
        }
        //        fonts.add(loadFont("BINHLBI.TTF"));
        RenderingHints localRenderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        localRenderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        localGraphics2D.setRenderingHints(localRenderingHints);
        localGraphics2D.fillRect(0, 0, width, height);
        localGraphics2D.setColor(new Color(50, 50, 50));
        Random localRandom = new Random();
        int i = 0;
        int j = 0;
        for (int k = 0; k < CaptchaText.length(); k++) {
            i += 25 + Math.abs(localRandom.nextInt()) % 5;
            j = 25 + Math.abs(localRandom.nextInt()) % 20;
            int tmp = localRandom.nextInt(fonts.size() - 1);
            localGraphics2D.setFont(fonts.get(tmp));

            localGraphics2D.drawChars(CaptchaText.toCharArray(), k, 1, i, j);
        }
        localBufferedImage = getDistortedImage(localBufferedImage);
        Graphics2D localGraphics2D2 = localBufferedImage.createGraphics();
        localGraphics2D2.setRenderingHints(localRenderingHints);
        //        localGraphics2D2.fillRect(0, 0, width, height);
        localGraphics2D2.setColor(new Color(50, 50, 50));
        CubicCurve2D c = new CubicCurve2D.Double();// draw QuadCurve2D.Float with set coordinates
        for (int l = 0; l < 7; l++) {
            int x1 = Util.rand(0, width / 2);
            ;
            int x2 = Util.rand(width / 2, width);
            int y1 = Util.rand(0, height);
            int y2 = Util.rand(0, height);
            int ctrlx1 = (x1 + x2) / 4 * Util.rand(1, 3);
            int ctrly1 = y1;
            int ctrlx2 = (x1 + x2) / 4 * Util.rand(1, 3);
            int ctrly2 = y2;

            c.setCurve(x1, y1, ctrlx2, ctrly2, ctrlx1, ctrly1, x2, y2);
            localGraphics2D2.draw(c);
            //            localGraphics2D2.drawLine(randomX1(), randomY1(), randomX2(), randomY2());
        }

        localGraphics2D.dispose();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return null;
    }
    return localBufferedImage;
}

From source file:eu.udig.style.advanced.points.PointStyleManager.java

private TableViewer createStylesTableViewer(Composite parent) {
    final StyleFilter filter = new StyleFilter();
    final Text searchText = new Text(parent, SWT.BORDER | SWT.SEARCH);
    searchText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
    searchText.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent ke) {
            filter.setSearchText(searchText.getText());
            stylesViewer.refresh();// www  . j  ava 2s  .  c o  m
        }

    });

    stylesViewer = new TableViewer(parent, SWT.SINGLE | SWT.BORDER);
    Table table = stylesViewer.getTable();
    GridData tableGD = new GridData(SWT.FILL, SWT.FILL, true, true);
    tableGD.heightHint = 200;
    table.setLayoutData(tableGD);

    stylesViewer.addFilter(filter);
    stylesViewer.setContentProvider(new IStructuredContentProvider() {
        public Object[] getElements(Object inputElement) {
            if (inputElement instanceof List<?>) {
                List<?> styles = (List<?>) inputElement;
                StyleWrapper[] array = (StyleWrapper[]) styles.toArray(new StyleWrapper[styles.size()]);
                return array;
            }
            return null;
        }

        public void dispose() {
        }

        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
        }
    });

    stylesViewer.setLabelProvider(new LabelProvider() {
        public Image getImage(Object element) {
            if (element instanceof StyleWrapper) {
                StyleWrapper styleWrapper = (StyleWrapper) element;
                List<FeatureTypeStyleWrapper> featureTypeStyles = styleWrapper
                        .getFeatureTypeStylesWrapperList();
                int iconSize = 48;
                BufferedImage image = new BufferedImage(iconSize, iconSize, BufferedImage.TYPE_INT_ARGB);
                Graphics2D g2d = image.createGraphics();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                for (FeatureTypeStyleWrapper featureTypeStyle : featureTypeStyles) {
                    List<RuleWrapper> rulesWrapperList = featureTypeStyle.getRulesWrapperList();
                    BufferedImage tmpImage = Utilities.pointRulesWrapperToImage(rulesWrapperList, iconSize,
                            iconSize);
                    g2d.drawImage(tmpImage, 0, 0, null);
                }
                g2d.dispose();
                Image convertToSWTImage = AWTSWTImageUtils.convertToSWTImage(image);
                return convertToSWTImage;
            }
            return null;
        }

        public String getText(Object element) {
            if (element instanceof StyleWrapper) {
                StyleWrapper styleWrapper = (StyleWrapper) element;
                String styleName = styleWrapper.getName();
                if (styleName == null || styleName.length() == 0) {
                    styleName = Utilities.DEFAULT_STYLENAME;
                    styleName = Utilities.checkSameNameStyle(getStyles(), styleName);
                    styleWrapper.setName(styleName);
                }
                return styleName;
            }
            return ""; //$NON-NLS-1$
        }
    });

    stylesViewer.addSelectionChangedListener(new ISelectionChangedListener() {

        public void selectionChanged(SelectionChangedEvent event) {
            ISelection selection = event.getSelection();
            if (!(selection instanceof IStructuredSelection)) {
                return;
            }
            IStructuredSelection sel = (IStructuredSelection) selection;
            if (sel.isEmpty()) {
                return;
            }

            Object selectedItem = sel.getFirstElement();
            if (selectedItem == null) {
                // unselected, show empty panel
                return;
            }

            if (selectedItem instanceof StyleWrapper) {
                currentSelectedStyleWrapper = (StyleWrapper) selectedItem;
            }
        }

    });
    return stylesViewer;
}

From source file:FieldValidator.java

@Override
public void paint(Graphics g, JComponent c) {
    super.paint(g, c);

    JLayer jlayer = (JLayer) c;
    JFormattedTextField ftf = (JFormattedTextField) jlayer.getView();
    if (!ftf.isEditValid()) {
        Graphics2D g2 = (Graphics2D) g.create();

        // Paint the red X.
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        int w = c.getWidth();
        int h = c.getHeight();
        int s = 8;
        int pad = 4;
        int x = w - pad - s;
        int y = (h - s) / 2;
        g2.setPaint(Color.red);//w ww  . j av a2 s  . c om
        g2.fillRect(x, y, s + 1, s + 1);
        g2.setPaint(Color.white);
        g2.drawLine(x, y, x + s, y + s);
        g2.drawLine(x, y + s, x + s, y);

        g2.dispose();
    }
}