Example usage for java.awt Font deriveFont

List of usage examples for java.awt Font deriveFont

Introduction

In this page you can find the example usage for java.awt Font deriveFont.

Prototype

public Font deriveFont(Map<? extends Attribute, ?> attributes) 

Source Link

Document

Creates a new Font object by replicating the current Font object and applying a new set of font attributes to it.

Usage

From source file:uk.ac.ed.epcc.webapp.charts.jfreechart.JFreeBarTimeChartData.java

@Override
public JFreeChart getJFreeChart() {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    double counts[] = ds.getCounts();
    String legends[] = ds.getLegends();
    int max_len = 0;
    for (int i = 0; i < ds.getNumSets(); i++) {
        if (legends != null && legends.length > i) {
            dataset.addValue(new Double(counts[i]), "Series-1", legends[i]);
            int leg_len = legends[i].length();
            if (leg_len > max_len) {
                max_len = leg_len;//  w  ww  .  jav a  2  s  . c  o m
            }
            //System.out.println(legends[i] + counts[i]);
        } else {
            dataset.addValue(new Double(counts[i]), "Series-1", Integer.toString(i));
        }
    }
    CategoryDataset data = dataset;

    JFreeChart chart = ChartFactory.createBarChart(title, null, quantity, data, PlotOrientation.VERTICAL, false, // include legends
            false, // tooltips
            false // urls
    );

    CategoryPlot categoryPlot = chart.getCategoryPlot();
    CategoryAxis axis = categoryPlot.getDomainAxis();
    if (max_len > 8 || ds.getNumSets() > 16 || (max_len * ds.getNumSets()) > 50) {
        axis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
    }
    Font tickLabelFont = axis.getTickLabelFont();
    if (ds.getNumSets() > 24) {
        axis.setTickLabelFont(tickLabelFont.deriveFont(tickLabelFont.getSize() - 2.0F));
    }
    Font labelFont = axis.getLabelFont();
    axis.setMaximumCategoryLabelLines(3);
    //axis.setLabelFont(labelFont.d);
    // axis.setLabel("Pingu"); This works so we can modify

    return chart;

}

From source file:net.sf.jasperreports.engine.util.JRFontUtil.java

/**
 * Returns a java.awt.Font instance by converting a JRFont instance.
 * Mostly used in combination with third-party visualization packages such as JFreeChart (for chart themes).
 * Unless the font parameter is null, this method always returns a non-null AWT font, regardless whether it was
 * found in the font extensions or not. This is because we do need a font to draw with and there is no point
 * in raising a font missing exception here, as it is not JasperReports who does the drawing. 
 *///from   ww w  . ja  v a  2 s.c om
public static Font getAwtFont(JRFont font, Locale locale) {
    if (font == null) {
        return null;
    }

    // ignoring missing font as explained in the Javadoc
    Font awtFont = getAwtFontFromBundles(font.getFontName(),
            ((font.isBold() ? Font.BOLD : Font.PLAIN) | (font.isItalic() ? Font.ITALIC : Font.PLAIN)),
            font.getFontSize(), locale, true);

    if (awtFont == null) {
        awtFont = new Font(getAttributesWithoutAwtFont(new HashMap<Attribute, Object>(), font));
    } else {
        // add underline and strikethrough attributes since these are set at
        // style/font level
        Map<Attribute, Object> attributes = new HashMap<Attribute, Object>();
        if (font.isUnderline()) {
            attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
        }
        if (font.isStrikeThrough()) {
            attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
        }

        if (!attributes.isEmpty()) {
            awtFont = awtFont.deriveFont(attributes);
        }
    }

    return awtFont;
}

From source file:org.mbari.aved.ui.classifier.ClassModelListRenderer.java

/**
 * Set the default font and text/*from ww w .  ja  v  a  2s.co  m*/
 */
protected void setDefaultText(String missingText, Font normalFont) {
    if (missingImageFont == null) {
        missingImageFont = normalFont.deriveFont(Font.BOLD);
    }

    setFont(missingImageFont);
    setText(missingText);
}

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

protected void setupFont(Axis axis, String fieldName) {
    if (params.get(fieldName) instanceof Font) {
        axis.setTickLabelFont((Font) params.get(fieldName));
    } else {/*from w w  w .  ja  va2 s . c  om*/
        Font numFont = axis.getTickLabelFont();
        if (numFont != null) {
            axis.setTickLabelFont(numFont.deriveFont(6));
        }
    }
}

From source file:Paints.java

/** Draw the example */
public void paint(Graphics g1) {
    Graphics2D g = (Graphics2D) g1;
    // Paint the entire background using a GradientPaint.
    // The background color varies diagonally from deep red to pale blue
    g.setPaint(new GradientPaint(0, 0, new Color(150, 0, 0), WIDTH, HEIGHT, new Color(200, 200, 255)));
    g.fillRect(0, 0, WIDTH, HEIGHT); // fill the background

    // Use a different GradientPaint to draw a box.
    // This one alternates between deep opaque green and transparent green.
    // Note: the 4th arg to Color() constructor specifies color opacity
    g.setPaint(new GradientPaint(0, 0, new Color(0, 150, 0), 20, 20, new Color(0, 150, 0, 0), true));
    g.setStroke(new BasicStroke(15)); // use wide lines
    g.drawRect(25, 25, WIDTH - 50, HEIGHT - 50); // draw the box

    // The glyphs of fonts can be used as Shape objects, which enables
    // us to use Java2D techniques with letters Just as we would with
    // any other shape. Here we get some letter shapes to draw.
    Font font = new Font("Serif", Font.BOLD, 10); // a basic font
    Font bigfont = // a scaled up version
            font.deriveFont(AffineTransform.getScaleInstance(30.0, 30.0));
    GlyphVector gv = bigfont.createGlyphVector(g.getFontRenderContext(), "JAV");
    Shape jshape = gv.getGlyphOutline(0); // Shape of letter J
    Shape ashape = gv.getGlyphOutline(1); // Shape of letter A
    Shape vshape = gv.getGlyphOutline(2); // Shape of letter V

    // We're going to outline the letters with a 5-pixel wide line
    g.setStroke(new BasicStroke(5.0f));

    // We're going to fake shadows for the letters using the
    // following Paint and AffineTransform objects
    Paint shadowPaint = new Color(0, 0, 0, 100); // Translucent black
    AffineTransform shadowTransform = AffineTransform.getShearInstance(-1.0, 0.0); // Shear to the right
    shadowTransform.scale(1.0, 0.5); // Scale height by 1/2

    // Move to the baseline of our first letter
    g.translate(65, 270);/*from w ww  .  j  av a 2  s . c  o m*/

    // Draw the shadow of the J shape
    g.setPaint(shadowPaint);
    g.translate(15, 20); // Compensate for the descender of the J
    // transform the J into the shape of its shadow, and fill it
    g.fill(shadowTransform.createTransformedShape(jshape));
    g.translate(-15, -20); // Undo the translation above

    // Now fill the J shape with a solid (and opaque) color
    g.setPaint(Color.blue); // Fill with solid, opaque blue
    g.fill(jshape); // Fill the shape
    g.setPaint(Color.black); // Switch to solid black
    g.draw(jshape); // And draw the outline of the J

    // Now draw the A shadow
    g.translate(75, 0); // Move to the right
    g.setPaint(shadowPaint); // Set shadow color
    g.fill(shadowTransform.createTransformedShape(ashape)); // draw shadow

    // Draw the A shape using a solid transparent color
    g.setPaint(new Color(0, 255, 0, 125)); // Transparent green as paint
    g.fill(ashape); // Fill the shape
    g.setPaint(Color.black); // Switch to solid back
    g.draw(ashape); // Draw the outline

    // Move to the right and draw the shadow of the letter V
    g.translate(175, 0);
    g.setPaint(shadowPaint);
    g.fill(shadowTransform.createTransformedShape(vshape));

    // We're going to fill the next letter using a TexturePaint, which
    // repeatedly tiles an image. The first step is to obtain the image.
    // We could load it from an image file, but here we create it
    // ourselves by drawing a into an off-screen image. Note that we use
    // a GradientPaint to fill the off-screen image, so the fill pattern
    // combines features of both Paint classes.
    BufferedImage tile = // Create an image
            new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB);
    Graphics2D tg = tile.createGraphics(); // Get its Graphics for drawing
    tg.setColor(Color.pink);
    tg.fillRect(0, 0, 50, 50); // Fill tile background with pink
    tg.setPaint(new GradientPaint(40, 0, Color.green, // diagonal gradient
            0, 40, Color.gray)); // green to gray
    tg.fillOval(5, 5, 40, 40); // Draw a circle with this gradient

    // Use this new tile to create a TexturePaint and fill the letter V
    g.setPaint(new TexturePaint(tile, new Rectangle(0, 0, 50, 50)));
    g.fill(vshape); // Fill letter shape
    g.setPaint(Color.black); // Switch to solid black
    g.draw(vshape); // Draw outline of letter

    // Move to the right and draw the shadow of the final A
    g.translate(160, 0);
    g.setPaint(shadowPaint);
    g.fill(shadowTransform.createTransformedShape(ashape));

    g.fill(ashape); // Fill letter A
    g.setPaint(Color.black); // Revert to solid black
    g.draw(ashape); // Draw the outline of the A
}

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

/**
 * A demonstration application showing some bugs with tick labels in version 0.9.13
 *
 * @param title  the frame title./*from   w w  w .jav  a2s.  c o  m*/
 */
public XYTickLabelDemo(final String title) {

    super(title);
    this.chart = createChart();
    final ChartPanel chartPanel = new ChartPanel(this.chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(600, 270));

    final JPanel mainPanel = new JPanel(new BorderLayout());
    setContentPane(mainPanel);
    mainPanel.add(chartPanel);

    final JPanel optionsPanel = new JPanel();
    mainPanel.add(optionsPanel, BorderLayout.SOUTH);

    this.symbolicAxesCheckBox = new JCheckBox("Symbolic axes");
    this.symbolicAxesCheckBox.addActionListener(this);
    optionsPanel.add(this.symbolicAxesCheckBox);

    this.verticalTickLabelsCheckBox = new JCheckBox("Tick labels vertical");
    this.verticalTickLabelsCheckBox.addActionListener(this);
    optionsPanel.add(this.verticalTickLabelsCheckBox);

    this.fontSizeTextField = new JTextField(3);
    this.fontSizeTextField.addActionListener(this);
    optionsPanel.add(new JLabel("Font size:"));
    optionsPanel.add(this.fontSizeTextField);
    final ValueAxis axis = this.chart.getXYPlot().getDomainAxis();
    this.fontSizeTextField.setText(DEFAULT_FONT_SIZE + "");

    final XYPlot plot = this.chart.getXYPlot();
    Font ft = axis.getTickLabelFont();
    ft = ft.deriveFont((float) DEFAULT_FONT_SIZE);
    plot.getDomainAxis().setTickLabelFont(ft);
    plot.getRangeAxis().setTickLabelFont(ft);
    plot.getDomainAxis(1).setTickLabelFont(ft);
    plot.getRangeAxis(1).setTickLabelFont(ft);

    this.horizontalPlotCheckBox = new JCheckBox("Plot horizontal");
    this.horizontalPlotCheckBox.addActionListener(this);
    optionsPanel.add(this.horizontalPlotCheckBox);
}

From source file:utybo.branchingstorytree.swing.visuals.AboutDialog.java

@SuppressWarnings("unchecked")
public AboutDialog(OpenBSTGUI parent) {
    super(parent);
    setTitle(Lang.get("about.title"));
    setModalityType(ModalityType.APPLICATION_MODAL);

    JPanel banner = new JPanel(new FlowLayout(FlowLayout.CENTER));
    banner.setBackground(OpenBSTGUI.OPENBST_BLUE);
    JLabel lblOpenbst = new JLabel(new ImageIcon(Icons.getImage("FullLogoWhite", 48)));
    lblOpenbst.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    banner.add(lblOpenbst, "flowx,cell 0 0,alignx center");
    getContentPane().add(banner, BorderLayout.NORTH);

    JPanel pan = new JPanel();
    pan.setLayout(new MigLayout("insets 10, gap 10px", "[grow]", "[][][grow]"));
    getContentPane().add(pan, BorderLayout.CENTER);

    JLabel lblWebsite = new JLabel("https://utybo.github.io/BST/");
    Font f = lblWebsite.getFont();
    @SuppressWarnings("rawtypes")
    Map attrs = f.getAttributes();
    attrs.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
    lblWebsite.setFont(f.deriveFont(attrs));
    lblWebsite.setForeground(OpenBSTGUI.OPENBST_BLUE);
    lblWebsite.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    lblWebsite.addMouseListener(new MouseAdapter() {
        @Override/*  w  w w. ja  v a2  s  . c o m*/
        public void mouseClicked(MouseEvent e) {
            if (Desktop.isDesktopSupported()) {
                try {
                    Desktop.getDesktop().browse(new URL("https://utybo.github.io/BST/").toURI());
                } catch (IOException | URISyntaxException e1) {
                    OpenBST.LOG.warn("Exception when trying to open website", e1);
                }
            }
        }
    });
    pan.add(lblWebsite, "cell 0 0,alignx center");

    JLabel lblVersion = new JLabel(Lang.get("about.version").replace("$v", OpenBST.VERSION));
    pan.add(lblVersion, "flowy,cell 0 1");

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBorder(new LineBorder(pan.getBackground().darker(), 1, false));
    pan.add(scrollPane, "cell 0 2,grow");

    JTextArea textArea = new JTextArea();
    textArea.setMargin(new Insets(5, 5, 5, 5));
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    textArea.setFont(new Font(textArea.getFont().getFontName(), Font.PLAIN, (int) (Icons.getScale() * 11)));

    try (InputStream in = getClass().getResourceAsStream("/utybo/branchingstorytree/swing/about.txt");) {
        textArea.setText(IOUtils.toString(in, StandardCharsets.UTF_8));
    } catch (IOException ex) {
        OpenBST.LOG.warn("Loading about information failed", ex);
    }
    textArea.setEditable(false);
    textArea.setCaretPosition(0);
    scrollPane.setViewportView(textArea);

    JLabel lblTranslatedBy = new JLabel(Lang.get("author"));
    pan.add(lblTranslatedBy, "cell 0 1");

    setSize((int) (Icons.getScale() * 450), (int) (Icons.getScale() * 400));
    setLocationRelativeTo(parent);
}

From source file:uk.co.modularaudio.mads.base.oscilloscope.ui.OscilloscopeDisplayUiJComponent.java

private void paintIntoImage(final Graphics g, final OscilloscopeWriteableScopeData scopeData) {
    //      Graphics2D g2d = (Graphics2D)g;
    //      Rectangle clipBounds = g.getClipBounds();
    final Font f = g.getFont();
    final Font newFont = f.deriveFont(12);
    g.setFont(newFont);// w  ww  . j  a v  a  2  s .  c o  m
    final int x = 0;
    final int y = 0;

    newMaxMag0 = 0.5f;
    newMaxMag1 = 0.5f;

    final int width = getWidth();
    final int height = getHeight();

    final int plotWidth = width - (SCALE_WIDTH * 2);
    final int plotStart = SCALE_WIDTH;
    final int plotHeight = getHeight();

    //      g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
    g.setColor(Color.BLACK);
    g.fillRect(x, y, width, height);

    if (scopeData != null) {

        final int numSamplesInBuffer = scopeData.desiredDataLength;

        final float[] float0Data = scopeData.floatBuffer0;
        final FloatType float0Type = scopeData.floatBuffer0Type;
        switch (float0Type) {
        case AUDIO:
            maxMag0 = 1.0f;
            break;
        case CV:
            break;
        }
        final boolean displayFloat0 = scopeData.float0Written;

        final float[] float1Data = scopeData.floatBuffer1;
        final FloatType float1Type = scopeData.floatBuffer1Type;
        switch (float1Type) {
        case AUDIO:
            maxMag1 = 1.0f;
            break;
        case CV:
            break;
        }
        final boolean displayFloat1 = scopeData.float1Written;

        if (displayFloat0) {
            // Float data draw
            g.setColor(Color.RED);
            drawScale(g, height, maxMag0, 0);
            plotAllDataValues(g, plotWidth, plotStart, plotHeight, numSamplesInBuffer, float0Data, true);
        }

        if (displayFloat1) {
            // CV data draw
            g.setColor(Color.YELLOW);
            drawScale(g, height, maxMag1, plotStart + plotWidth);
            plotAllDataValues(g, plotWidth, plotStart, plotHeight, numSamplesInBuffer, float1Data, false);
        }
        maxMag0 = newMaxMag0;
        maxMag1 = newMaxMag1;
    }
}

From source file:org.datacleaner.widgets.visualization.JobGraphTransformers.java

private Font font(Font font, float fontFactor) {
    if (fontFactor == 1.0) {
        return font;
    }/*  ww w  .  j a va 2 s.c om*/
    return font.deriveFont(font.getSize() * fontFactor);
}

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

@SuppressWarnings("unchecked")
@Override/*from   www .j av  a 2  s.com*/
public void initialize() throws GraphException {
    String title = getParam(GraphSource.GRAPH_TITLE, String.class, DEFAULT_TITLE);
    boolean legend = getParam(GraphSource.GRAPH_LEGEND, Boolean.class, DEFAULT_GRAPH_LEGEND);
    boolean graphToolTip = getParam(GraphSource.GRAPH_TOOL_TIP, Boolean.class, DEFAULT_GRAPH_TOOL_TIP);
    boolean graphDisplayLabel = getParam(GraphSource.GRAPH_DISPLAY_LABEL, Boolean.class, false);
    boolean legendBorder = getParam(GraphSource.LEGEND_BORDER, Boolean.class, DEFAULT_LEGEND_BORDER);
    boolean graphBorder = getParam(GraphSource.GRAPH_BORDER, Boolean.class, DEFAULT_GRAPH_BORDER);
    Font titleFont = getParam(GraphSource.GRAPH_FONT, Font.class, DEFAULT_GRAPH_TITLE_FONT);
    String noDataMessage = getParam(GraphSource.GRAPH_NO_DATA_MESSAGE, String.class,
            DEFAULT_GRAPH_NO_DATA_MESSAGE);
    PieGraphData pieGraphData = makeDataSet();
    Map<Comparable, Paint> colors = pieGraphData.colors;

    this.chart = ChartFactory.createPieChart(title, pieGraphData.data, false, graphToolTip, false);

    Paint backgroundColor = getParam(GraphSource.BACKGROUND_COLOR, Paint.class, DEFAULT_BACKGROUND_COLOR);
    Paint plotColor = getParam(JFreeChartTimeSeriesGraphSource.PLOT_COLOR, Paint.class, backgroundColor);
    Paint labelColor = getParam(JFreeChartTimeSeriesGraphSource.GRAPH_LABEL_BACKGROUND_COLOR, Paint.class,
            DEFAULT_BACKGROUND_COLOR);

    this.chart.setBackgroundPaint(backgroundColor);
    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(plotColor);
    plot.setNoDataMessage(noDataMessage);

    if (!graphDisplayLabel) {
        plot.setLabelGenerator(null);
    } else {
        plot.setInteriorGap(0.001);
        plot.setMaximumLabelWidth(.3);
        //           plot.setIgnoreNullValues(true);
        plot.setIgnoreZeroValues(true);
        plot.setShadowPaint(null);
        //           plot.setOutlineVisible(false);
        //TODO use title font?
        Font font = plot.getLabelFont();
        plot.setLabelLinkStyle(PieLabelLinkStyle.CUBIC_CURVE);
        plot.setLabelFont(font.deriveFont(font.getSize2D() * .75f));
        plot.setLabelBackgroundPaint(labelColor);
        plot.setLabelShadowPaint(null);
        plot.setLabelOutlinePaint(null);
        plot.setLabelGap(0.001);
        plot.setLabelLinkMargin(0.0);
        plot.setLabelLinksVisible(true);
        //           plot.setSimpleLabels(true);
        //           plot.setCircular(true);
    }

    if (!graphBorder) {
        plot.setOutlineVisible(false);
    }

    if (title != null && !"".equals(title)) {
        TextTitle title1 = new TextTitle();
        title1.setText(title);
        title1.setFont(titleFont);
        title1.setPadding(3, 2, 5, 2);
        chart.setTitle(title1);
    } else {
        chart.setTitle((TextTitle) null);
    }
    plot.setLabelPadding(new RectangleInsets(1, 1, 1, 1));
    //Makes a wrapper for the legend to remove the border around it
    if (legend) {
        LegendTitle legend1 = new LegendTitle(chart.getPlot());
        BlockContainer wrapper = new BlockContainer(new BorderArrangement());

        if (legendBorder) {
            wrapper.setFrame(new BlockBorder(1, 1, 1, 1));
        } else {
            wrapper.setFrame(new BlockBorder(0, 0, 0, 0));
        }

        BlockContainer items = legend1.getItemContainer();
        items.setPadding(2, 10, 5, 2);
        wrapper.add(items);
        legend1.setWrapper(wrapper);
        legend1.setPosition(RectangleEdge.BOTTOM);
        legend1.setHorizontalAlignment(HorizontalAlignment.CENTER);

        if (params.get(GraphSource.LEGEND_FONT) instanceof Font) {
            legend1.setItemFont(((Font) params.get(GraphSource.LEGEND_FONT)));
        }

        chart.addSubtitle(legend1);
        plot.setLegendLabelGenerator(new PieGraphLabelGenerator());
    }

    for (Comparable category : colors.keySet()) {
        plot.setSectionPaint(category, colors.get(category));
    }

    plot.setToolTipGenerator(new PieGraphToolTipGenerator(pieGraphData));
    plot.setURLGenerator(new PieGraphURLGenerator(pieGraphData));

    initialized = true;
}