Java Code Examples for java.awt.Font#deriveFont()

The following examples show how to use java.awt.Font#deriveFont() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PFontHandler.java    From PolyGlot with MIT License 6 votes vote down vote up
/**
 * Attempts to load the given font from the OS's font folder (due to Java's
 * ligature problems)
 *
 * @param fontFamily
 * @return returns loaded font file on success, null otherwise
 */
public static Font loadFontFromOSFileFolder(String fontFamily) {
    Font ret = null;
    try {
        File fontFile = getFontFile(fontFamily);
        if (fontFile != null && fontFile.exists()) {
            ret = Font.createFont(Font.TRUETYPE_FONT, fontFile);
            Map attributes = ret.getAttributes();
            attributes.put(TextAttribute.LIGATURES, TextAttribute.LIGATURES_ON);
            ret = ret.deriveFont(attributes);
        }
    } catch (Exception e) {
        IOHandler.writeErrorLog(e);
        // do nothing here. Failure means returning null
    }

    return ret;
}
 
Example 2
Source File: LinkButton.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void init(Action al) {
    setOpaque(false);
    setBorder(BorderFactory.createEmptyBorder());
    setBorderPainted(false);
    setFocusPainted(false);
    setFocusable(false);
    setContentAreaFilled(false);
    setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    setModel(new Model());
    if (null != al) {
        addActionListener(al);
        setForeground(ColorManager.getDefault().getLinkColor());
    } else {
        setEnabled(false);
        setForeground(ColorManager.getDefault().getDisabledColor());
    }
    Font font = UIManager.getFont("Tree.font");//NOI18N
    if (underlined) {
        Map<TextAttribute, Object> map = new HashMap<TextAttribute, Object>();
        map.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_LOW_ONE_PIXEL);
        font = font.deriveFont(map);
    }
    setFont(font);
}
 
Example 3
Source File: JavaFontRenderingBox.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public JavaFontRenderingBox(String str, int type, float size, Font f, boolean kerning) {
    this.size = size;

    if (kerning && KERNING != null) {
        Map<TextAttribute, Object> map = new Hashtable<TextAttribute, Object>();
        map.put(KERNING, KERNING_ON);
        map.put(LIGATURES, LIGATURES_ON);
        f = f.deriveFont(map);
    }

    this.text = new TextLayout(str, f.deriveFont(type), TEMPGRAPHIC.getFontRenderContext());
    Rectangle2D rect = text.getBounds();
    this.height = (float) (-rect.getY() * size / 10);
    this.depth = (float) (rect.getHeight() * size / 10) - this.height;
    this.width = (float) ((rect.getWidth() + rect.getX() + 0.4f) * size / 10);
}
 
Example 4
Source File: FontPanel.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public FontPanel( Font2DTest demo, JFrame f ) {
    f2dt = demo;
    parent = f;

    verticalBar = new JScrollBar ( JScrollBar.VERTICAL );
    fc = new FontCanvas();

    this.setLayout( new BorderLayout() );
    this.add( "Center", fc );
    this.add( "East", verticalBar );

    verticalBar.addAdjustmentListener( this );
    this.addComponentListener( new ComponentAdapter() {
        public void componentResized( ComponentEvent e ) {
            updateBackBuffer = true;
            updateFontMetrics = true;
        }
    });

    /// Initialize font and its infos
    testFont = new Font(fontName, fontStyle, (int)fontSize);
    if ((float)((int)fontSize) != fontSize) {
        testFont = testFont.deriveFont(fontSize);
    }
    updateFontInfo();
}
 
Example 5
Source File: PFontHandler.java    From PolyGlot with MIT License 6 votes vote down vote up
/**
 * Fetches and returns default button font nonstatic
 *
 * @return Font to default buttons to
 * @throws java.io.IOException if unable to load font
 */
private Font getMenuFontInternal() throws IOException {
    Font ret;
    try (InputStream tmp = this.getClass().getResourceAsStream(PGTUtil.BUTTON_FONT_LOCATION)) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        ret = Font.createFont(Font.TRUETYPE_FONT, tmp);
        ret = ret.deriveFont((float) 12); // default to size 12 font
        if (ret != null) {
            ge.registerFont(ret);
        }
    } catch (Exception e) {
        throw new IOException("Unable to load button font.", e);
    }

    return ret;
}
 
Example 6
Source File: SinglePointFont.java    From mil-sym-java with Apache License 2.0 5 votes vote down vote up
/**
 * Font used to render force elements (units).
 * @param size
 * @return 
 */
public Font getUnitFont(float size)
{
    //load font from resource
    InputStream fontStream = _instance.getClass().getClassLoader().getResourceAsStream("FONTS/UnitFont.ttf");
    //InputStream fontStream = _unitFontStream;

    Font newFont = null;
    try
    {
        //create font
        newFont = Font.createFont(Font.TRUETYPE_FONT, fontStream);
    }
    catch(FontFormatException ffe)
    {
        ErrorLogger.LogException(this.getClass().getName() ,"getUnitFont()",
                new RendererException("UnitFont failed to load.", ffe));
    }
    catch(IOException ioe)
    {
        ErrorLogger.LogException(this.getClass().getName() ,"getUnitFont()",
                new RendererException("UnitFont failed to load.", ioe));
    }
    catch(Exception exc)
    {
        ErrorLogger.LogException(this.getClass().getName() ,"getUnitFont()",
                new RendererException("UnitFont failed to load.", exc));
    }

    //resize font
    newFont = newFont.deriveFont(Font.TRUETYPE_FONT, size);
    //return font
    return newFont;

}
 
Example 7
Source File: FontPanel.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void setFontParams(String name, float size,
                          int style, int transform) {
    boolean fontModified = false;
    if ( !name.equals( fontName ) || style != fontStyle )
      fontModified = true;

    fontName = name;
    fontSize = size;
    fontStyle = style;
    fontTransform = transform;

    /// Recreate the font as specified
    testFont = new Font(fontName, fontStyle, (int)fontSize);
    if ((float)((int)fontSize) != fontSize) {
        testFont = testFont.deriveFont(fontSize);
    }

    if ( fontTransform != NONE ) {
        AffineTransform at = getAffineTransform( fontTransform );
        testFont = testFont.deriveFont( at );
    }
    updateBackBuffer = true;
    updateFontMetrics = true;
    fc.repaint();
    if ( fontModified ) {
        /// Tell main panel to update the font info
        updateFontInfo();
        f2dt.fireUpdateFontInfo();
    }
}
 
Example 8
Source File: FontUtils.java    From scrimage with Apache License 2.0 5 votes vote down vote up
public static Font createTrueType(InputStream in, int size) throws IOException, FontFormatException {
   assert (in != null);
   Font font = Font.createFont(Font.TRUETYPE_FONT, in);
   GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
   ge.registerFont(font);
   return font.deriveFont(Font.PLAIN, size);
}
 
Example 9
Source File: StatusImage.java    From jenkins-status-badges-plugin with MIT License 5 votes vote down vote up
public int measureText( String text )
    throws FontFormatException, IOException
{
    URL fontURL =
        new URL( Jenkins.getInstance().pluginManager.getPlugin( "status-badges" ).baseResourceURL,
                 "fonts/verdana.ttf" );
    InputStream fontStream = fontURL.openStream();
    Font defaultFont = Font.createFont( Font.TRUETYPE_FONT, fontStream );
    defaultFont = defaultFont.deriveFont( 11f );
    Canvas canvas = new Canvas();
    FontMetrics fontMetrics = canvas.getFontMetrics( defaultFont );
    return fontMetrics.stringWidth( text );
}
 
Example 10
Source File: ImageManufacture.java    From MyBox with Apache License 2.0 5 votes vote down vote up
public static void addText(Graphics2D g, String text,
        Font font, Color color, int x, int y,
        float opacity, int shadow, int angle,
        boolean isOutline) {
    try {
        AffineTransform saveAT = g.getTransform();
        AffineTransform affineTransform = new AffineTransform();
        affineTransform.rotate(Math.toRadians(angle), 0, 0);
        Font rotatedFont = font.deriveFont(affineTransform);
        if (shadow > 0) {  // Not blurred. Can improve
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            g.setColor(Color.GRAY);
            g.setFont(rotatedFont);
            g.drawString(text, x + shadow, y + shadow);
        }

        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));
        g.setColor(color);
        g.setFont(rotatedFont);
        if (isOutline) {
            FontRenderContext frc = g.getFontRenderContext();
            TextLayout textTl = new TextLayout(text, rotatedFont, frc);
            Shape outline = textTl.getOutline(null);
            AffineTransform transform = g.getTransform();
            transform.translate(x, y);
            g.transform(transform);
            g.draw(outline);
        } else {
            g.drawString(text, x, y);
        }
        g.setTransform(saveAT);
    } catch (Exception e) {
        logger.error(e.toString());
    }
}
 
Example 11
Source File: Scale.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * @param font The font to scale.
 * @return The scaled font.
 */
public Font scale(Font font) {
    if (mScale == 1) {
        return font;
    }
    return font.deriveFont((float) (font.getSize() * mScale));
}
 
Example 12
Source File: TabbedPaneUI.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected FontMetrics getFontMetrics() {
	Font font = tabPane.getFont();
	// selected tab is bold, to avoid resizing always assume bold and make tabs bigger
	font = font.deriveFont(Font.BOLD);
	return tabPane.getFontMetrics(font);
}
 
Example 13
Source File: NimbusDefaults.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public Object createValue(UIDefaults defaults) {
    Font f = defaults.getFont(parentKey);
    if (f != null) {
        // always round size for now so we have exact int font size
        // (or we may have lame looking fonts)
        float size = Math.round(f.getSize2D() * sizeOffset);
        int style = f.getStyle();
        if (bold != null) {
            if (bold.booleanValue()) {
                style = style | Font.BOLD;
            } else {
                style = style & ~Font.BOLD;
            }
        }
        if (italic != null) {
            if (italic.booleanValue()) {
                style = style | Font.ITALIC;
            } else {
                style = style & ~Font.ITALIC;
            }
        }
        return f.deriveFont(style, size);
    } else {
        return null;
    }
}
 
Example 14
Source File: TextTests.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public void init(TestEnvironment env, Result result) {
    // graphics
    graphics = env.getGraphics();

    // text
    String sname = (String)env.getModifier(tscriptList);
    int slen = env.getIntValue(tlengthList);
    text = getString(sname, slen);

    // chars
    chars = text.toCharArray();

    // font
    String fname = (String)env.getModifier(fnameList);
    if ("Physical".equals(fname)) {
        fname = physicalFontNameFor(sname, slen, text);
    }
    int fstyle = env.getIntValue(fstyleList);
    float fsize = ((Float)env.getModifier(fsizeList)).floatValue();
    AffineTransform ftx = (AffineTransform)env.getModifier(ftxList);
    font = new Font(fname, fstyle, (int)fsize);
    if (hasGraphics2D) {
        if (fsize != Math.floor(fsize)) {
            font = font.deriveFont(fsize);
        }
        if (!ftx.isIdentity()) {
            font = font.deriveFont(ftx);
        }
    }

    // graphics
    if (hasGraphics2D) {
        Graphics2D g2d = (Graphics2D)graphics;
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                             env.getModifier(taaList));
        g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
                             env.isEnabled(tfmTog)
                             ? RenderingHints.VALUE_FRACTIONALMETRICS_ON
                             : RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                             env.isEnabled(gaaTog)
                             ? RenderingHints.VALUE_ANTIALIAS_ON
                             : RenderingHints.VALUE_ANTIALIAS_OFF);
        g2d.transform((AffineTransform)env.getModifier(gtxList));
    }

    // set result
    result.setUnits(text.length());
    result.setUnitName("char");
}
 
Example 15
Source File: MaxAdvanceIsMax.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    GraphicsEnvironment e =
            GraphicsEnvironment.getLocalGraphicsEnvironment();
    Font[] fonts = e.getAllFonts();
    BufferedImage bi = new BufferedImage(500, 500,
            BufferedImage.TYPE_INT_RGB);
    for (AntialiasHint antialiasHint : antialiasHints) {
        for (Font f : fonts) {
            for (StyleAndSize styleAndSize : stylesAndSizes) {
                f = f.deriveFont(styleAndSize.style, styleAndSize.size);
                Graphics2D g2d = bi.createGraphics();
                g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                        antialiasHint.getHint());
                FontMetrics fm = g2d.getFontMetrics(f);
                int[] width;
                int maxWidth = -1;
                int maxAdvance = fm.getMaxAdvance();
                if (debug) {
                    System.out.println("Testing " + f + " in " +
                            antialiasHint);
                    System.out.println("getMaxAdvance: " + maxAdvance);
                }
                if (maxAdvance != -1) {
                    String failureMessage = null;
                    width = fm.getWidths();
                    for (int j = 0; j < width.length; j++) {
                        if (width[j] > maxWidth) {
                            maxWidth = width[j];
                        }
                        if (width[j] > maxAdvance) {
                            failureMessage = "FAILED: getMaxAdvance is " +
                                             "not max for font: " +
                                             f.toString() +
                                             " getMaxAdvance(): " +
                                             maxAdvance +
                                             " getWidths()[" + j + "]: " +
                                             width[j];
                            throw new Exception(failureMessage);
                        }
                    }
                }
                if (debug) {
                    System.out.println("Max char width: " + maxWidth);
                    System.out.println("PASSED");
                    System.out.println(".........................");
                }
            }
        }
    }
    System.out.println("TEST PASS - OK");
}
 
Example 16
Source File: FontManipulation.java    From pcgen with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static Font title(Font f)
{
	// XXX In Japanese, bold is not used and hardly readeable if small, just
	// use gothic/non gothic instead.
	return f.deriveFont(Font.BOLD);
}
 
Example 17
Source File: SystemUtilities.java    From ghidra with Apache License 2.0 3 votes vote down vote up
/**
 * Checks to see if the font size override setting is enabled and adjusts
 * the given font as necessary to match the override setting. If the setting
 * is not enabled, then <code>font</code> is returned.
 *
 * @param font
 *            The current font to adjust, if necessary.
 * @return a font object with the proper size.
 */
public static Font adjustForFontSizeOverride(Font font) {
	if (FONT_SIZE_OVERRIDE_VALUE == null) {
		return font;
	}

	return font.deriveFont((float) FONT_SIZE_OVERRIDE_VALUE.intValue());
}
 
Example 18
Source File: FontLibrary.java    From freecol with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Create a scaled {@code Font} where the scale factor is provided
 * explicitly in the parameter.
 * The equivalent of regular text, which would only complicate the
 * source code and slow down the game if used, would be:
 * createFont(FontType.NORMAL, FontSize.TINY, Font.PLAIN,
 *            gui.getImageLibrary().getScalingFactor());
 * 
 * @param fontType How the font should look like.
 * @param fontSize Its relative size.
 * @param style The font style for choosing plain, bold or italic.
 * @param scaleFactor The applied scale factor.
 * @return The created Font.
 */
public static Font createFont(FontType fontType, FontSize fontSize,
                              int style, float scaleFactor) {
    float scaledSize = calcScaledSize(fontSize, scaleFactor);
    String fontKey = getFontKey(fontType);
    Font font = (fontKey == null)
        ? mainFont
        : ResourceManager.getFont(fontKey);
    return font.deriveFont(style, scaledSize);
}
 
Example 19
Source File: FontManipulation.java    From pcgen with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * For less important text, like grayed out italic.
 * 
 * @param f
 *            base font
 */
public static Font less(Font f)
{
	return f.deriveFont(Font.ITALIC);
}
 
Example 20
Source File: FontManipulation.java    From pcgen with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * For bold italic font.
 * 
 * @param f
 *            base font
 */
public static Font bold_italic(Font f)
{
	return f.deriveFont(Font.BOLD | Font.ITALIC);
}