Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / June 2006

Tip: Looking for answers? Try searching our database.

font size in pixels?

Thread view: 
mitch - 27 Jun 2006 20:24 GMT
Suppose you want to use a font that's 12 pixels (not 12 points)
Arial.  How would you do it?  It seems like the answer has
something to do with FontRenderContext and AffineTransform
but does anybody have code that creates a font with a size in
pixels, or measures the size in pixels of an existing font?
Thanks.
Knute Johnson - 27 Jun 2006 22:04 GMT
> Suppose you want to use a font that's 12 pixels (not 12 points)
> Arial.  How would you do it?  It seems like the answer has
> something to do with FontRenderContext and AffineTransform
> but does anybody have code that creates a font with a size in
> pixels, or measures the size in pixels of an existing font?
> Thanks.

Mitch:

This is a program I wrote to do some of what you want.  I think the
problem you are going to find is that even two 12 point fonts have
different size characters when displayed.

package com.knutejohnson.redrock.test;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import com.knutejohnson.components.*;

public class PixelHeightTest extends JPanel {
    Font font = new Font("Dialog",Font.PLAIN,24);

    public PixelHeightTest() {
        setPreferredSize(new Dimension(640,480));
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent me) {
                Font f =
JFontChooser.showDialog(PixelHeightTest.this,font);
                if (f != null) {
                    font = f;
                    repaint();
                }
            }
        });
    }

    public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
         RenderingHints.VALUE_ANTIALIAS_ON);

        g2d.setColor(Color.BLACK);
        g2d.fillRect(0,0,getWidth(),getHeight());
        g2d.setColor(Color.WHITE);
        g.setFont(font);
        FontMetrics fm = g.getFontMetrics();
        int y = 40;
        int h = fm.getHeight();
        int a = fm.getAscent();
        int d = fm.getDescent();
        int l = fm.getLeading();
        int w = fm.stringWidth("1");
        g.drawString("Font: " + font.getName(),10,y);
        y += h;
        g.drawString("Height: " + Integer.toString(h),10,y);
        y += h;
        g.drawString("Ascent: " + Integer.toString(a),10,y);
        y += h;
        g.drawString("Descent: " + Integer.toString(d),10,y);
        y += h;
        g.drawString("Leading: " + Integer.toString(l),10,y);
        y += h;
        g.drawString("Char Width: " + Integer.toString(w),10,y);
        y += 2*h;
        g.drawLine(0,y,getWidth(),y);
        g.drawString("1234567890 ABCDEFG ggjjppqq",10,y);
        g.drawLine(0,y-a,getWidth(),y-a);
        y += h;
        g.drawString(Integer.toString(h) + " Pixels lower!
12LLll34",10,y);
        g.drawLine(0,y-a,getWidth(),y-a);
        y += h;
        g.drawString("bdfghijklpqt",10,y);
        y += 2*h;
        g.drawString("Click mouse here to change font.",10,y);

    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
                JFrame f = new JFrame("PixelHeightTest");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.add(new PixelHeightTest());
                f.pack();
                f.setVisible(true);
            }
        };
        EventQueue.invokeLater(r);
    }
}

//
//
//  JFontChooser
//
//

package com.knutejohnson.components;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class JFontChooser extends JComponent {
    private static final String alphabet =
"<html>abcdefghijklmnopqrstuvwxyz" +
     "<br>ABCDEFGHIJKLMNOPQRSTUVWXYZ<br>0123456789.:,;(:*!?')</html>";
    private static JDialog dialog;
    private static JComboBox fontBox;
    private static JLabel fontLabel;
    private static SpinnerNumberModel model;
    private static JCheckBox boldCheckBox,italicCheckBox;
    private static Font retcod;

    public static Font showDialog(Component comp, Font font) {
        JFrame frame = new JFrame();
        dialog = new JDialog(frame,"Choose Font",true);
        dialog.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                retcod = null;
            }
        });

        if (font == null)
           font = new Font("Dialog",Font.PLAIN,12);

        ActionListener al = new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                String ac = ae.getActionCommand();
                if (ac.equals("Font")) {
                    fontLabel.setFont(makeFont().deriveFont(16f));
                } else if (ac.equals("Bold")) {
                    fontLabel.setFont(makeFont().deriveFont(16f));
                } else if (ac.equals("Italic")) {
                    fontLabel.setFont(makeFont().deriveFont(16f));
                } else if (ac.equals("OK")) {
                    retcod = makeFont();
                    dialog.setVisible(false);
                } else if (ac.equals("Cancel")) {
                    retcod = null;
                    dialog.setVisible(false);
                }
            }
        };

        dialog.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        c.gridx = c.gridy = 0;
        c.insets = new Insets(8,8,8,8);

        GraphicsEnvironment ge =
         GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fonts = ge.getAvailableFontFamilyNames();

        fontLabel = new JLabel(alphabet);
        fontLabel.setPreferredSize(new Dimension(340,80));
        fontLabel.setFont(font.deriveFont(16f));
        dialog.add(fontLabel,c);

        ++c.gridy;
        fontBox = new JComboBox(fonts);
        fontBox.setSelectedItem(font.getFamily());
        fontBox.setActionCommand("Font");
        fontBox.addActionListener(al);
        dialog.add(fontBox,c);

        ++c.gridy;
        JPanel rowPanel = new JPanel(new
FlowLayout(FlowLayout.CENTER,16,0));
        JPanel p = new JPanel();
        model = new SpinnerNumberModel(font.getSize(),1,120,1);
        model.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent ce) {
                fontLabel.setFont(makeFont().deriveFont(16f));
            }
        });
        JSpinner sizeSpinner = new JSpinner(model);
        p.add(sizeSpinner);
        JLabel l = new JLabel("Size");
        p.add(l);
        rowPanel.add(p);

        boldCheckBox = new JCheckBox("Bold",font.isBold());
        boldCheckBox.addActionListener(al);
        rowPanel.add(boldCheckBox);

        italicCheckBox = new JCheckBox("Italic", font.isItalic());
        italicCheckBox.addActionListener(al);
        rowPanel.add(italicCheckBox);
        dialog.add(rowPanel,c);

        ++c.gridy;
        p = new JPanel();
        p.setLayout(new GridLayout(1,2,10,0));
        JButton okButton = new JButton("OK");
        okButton.addActionListener(al);
        dialog.getRootPane().setDefaultButton(okButton);
        p.add(okButton);

        JButton cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(al);
        p.add(cancelButton);
        dialog.add(p,c);

        dialog.pack();
        dialog.setLocationRelativeTo(comp);
        dialog.setVisible(true);
        dialog.dispose();

        return retcod;
    }

    public static Font showDialog(Component comp) {
        return showDialog(comp,comp.getFont());
    }

    private static Font makeFont() {
        String name = (String)fontBox.getSelectedItem();
        int style = (boldCheckBox.isSelected() ? Font.BOLD : Font.PLAIN) |
         (italicCheckBox.isSelected() ? Font.ITALIC : Font.PLAIN);
        int size = model.getNumber().intValue();
        return new Font(name,style,size);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
                final JFrame frame = new JFrame();
                frame.setLayout(new FlowLayout());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                final JButton b = new JButton("Open Dialog");
                b.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        Font retcod =
JFontChooser.showDialog(b,b.getFont());
                        if (retcod != null)
                            b.setFont(retcod);
                        System.out.println(retcod);
                    }
                });
                frame.add(b);

                frame.setSize(640,480);
                frame.setVisible(true);
            }
        };
        EventQueue.invokeLater(r);
    }
}

Signature

Knute Johnson
email s/nospam/knute/

Jeffrey H. Coffield - 28 Jun 2006 05:20 GMT
> Suppose you want to use a font that's 12 pixels (not 12 points)
> Arial.  How would you do it?  It seems like the answer has
> something to do with FontRenderContext and AffineTransform
> but does anybody have code that creates a font with a size in
> pixels, or measures the size in pixels of an existing font?
> Thanks.

The basic problem here is what a 12 point font really is. The point size
of a font is actually the design distance from the baseline of one row
of text to the baseline of the next row of text including the designed
whitespace between the rows of characters. The actual height of an upper
case A in most fonts is about 70% to 75% of the point size. Also a point
is only approximated by and not exactly equal to 1/72 of an inch and is
independent of the size of a pixel. A 12 pixel font on a 4800 dpi image
setter would be very small. A 12 pixel font would also be a different
size if a monitor was at 100 pixels/inch instead of 75 pixels/inch.

Jeff C.
Oliver Wong - 29 Jun 2006 19:50 GMT
> Suppose you want to use a font that's 12 pixels (not 12 points)
> Arial.  How would you do it?  It seems like the answer has
> something to do with FontRenderContext and AffineTransform
> but does anybody have code that creates a font with a size in
> pixels, or measures the size in pixels of an existing font?
> Thanks.

   I usually make a whole bunch of FontMetrics and do a binary search. E.g.
12pt too small? What about 24pt? Too big? How about 18 pt? etc.

   You can cache the results in a map, e.g.: 12px -> 14.2pt, 13px ->
14.4pt, etc.

   - Oliver


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.