Java: Fonts and Pixels - java

I'm making a game and in the menu I want to display the text in the center of the screen.
Is there a way in Java to get/calculate the width of a piece of text in a specified font with specified size and style.
Martijn

The FontMetrics.stringWidth method does just that -- it will return the width in pixels for a given String.
One can obtain the FontMetrics from a Graphics object by the getFontMetrics method.
For example:
g.setFont(new Font("Serif", Font.BOLD, 24));
int width = g.getFontMetrics().stringWidth("Hello World!");
System.out.println(width);
The result was:
135

In the class Font you have methods such like getLineMetrics or getStringBounds that may help you.

Just use a JLabel that is center aligned and the proper layout manager and you don't have to worry about this.

JLabel label = new JLabel("Text");
frame.add(label , SwingConstants.CENTER);

Related

JLabel's text is in the middle of the hitbox

I have created a JLabel and draw a long String on it. But, the problem is, however long is the content, the content always display at the middle of the label's box! I want to push the text to the top of the box.
How can I fix it? Thank you so much!
Font times = new Font("Times New Roman", Font.CENTER_BASELINE, 13);
JLabel mess = new JLabel();
mess.setFont(times);
mess.setLocation(300, 125);
mess.setSize(250, 200);
mess.setText(message);
mess.setForeground(Color.WHITE);
getContentPane().add(mess);

setBounds value for width that will set width to minimum?

Is there a value that can be put into setBounds to set the width to the minimum needed?
JLabel title = new JLabel("Title Text");
title.setBounds(50, 20, ?, 13);
Rather than using guess & check to find the minimum width, is there a value I can use?
If you already know the text that will be in the JLabel (i.e., if that text won't change after being assigned once), there is no need to set the minimum width; the JLabel should do so automatically.

How to set String's font size, style in Java using the Font class?

Suppose I have a String, "Hello World". I want to change the style of this string to a BOLD font, and set the size of all the characters from 12 to 18 [pt]. After that I want to use this string in a JLabel and JButton. How can I do that?
Font myFont = new Font("Serif", Font.BOLD, 12);, then use a setFont method on your components like
JButton b = new JButton("Hello World");
b.setFont(myFont);
Look here http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#deriveFont%28float%29
JComponent has a setFont() method. You will control the font there, not on the String.
Such as
JButton b = new JButton();
b.setFont(b.getFont().deriveFont(18.0f));

JFreeChart - wrong chart font

I have a problem with XYLineChart. I don't know how to set the chart font to look like Swing components. When I use this:
chart.setTitle(new TextTitle("Tahoma title, style plain, size 11", new Font("Tahoma", Font.PLAIN, 11)));
It is still wrong :(
EDIT: When I create the chart in a new frame, the font in the title is good. How do I set all the labels, axis titles, and other texts to the same font size, without bold?
SOLVED :)
public static void changeStyle(JFreeChart chart) {
final StandardChartTheme chartTheme = (StandardChartTheme)StandardChartTheme.createJFreeTheme();
final Font font = new Font("Tahoma", Font.PLAIN, 11);
final Color color = new Color(0, 0, 0);
chartTheme.setExtraLargeFont(font);
chartTheme.setLargeFont(font);
chartTheme.setRegularFont(font);
chartTheme.setSmallFont(font);
chartTheme.setAxisLabelPaint(color);
chartTheme.setLegendItemPaint(color);
chartTheme.setItemLabelPaint(color);
chartTheme.apply(chart);
}
If you want to change the existing title's font, do something like this:
chart.getTitle().setFont(new Font("Tahoma", Font.PLAIN, 11));
Addendum:
How do I change all items' fonts, e.g. labels, axis, etc.?
StandardChartTheme offers this capability by operating on individual chart components.
I don't know 2 things about XYLineCharts, but it looks like you might be setting the font on the wrong thing. Try setting it on different components.
Not much, but might get you going.
Good luck ;)
Damo

Java: Friendlier way to get an instance of FontMetrics

Is there a friendlier way to get an instance of FontMetrics than
FontMetrics fm = Graphics.getFontMetrics(Font);
I hate this way because of the following example:
If you want to create in a game a menu and you want all the menuitems in the center of the screen you need fontmetrics. But, mostly, menuitems are clickable. So I create an array of Rectangles and all the rectangles fits around the items, so when the mouse is pressed, I can simply use
for (int i = 0; i < rects.length; i++)
if (rects[i].contains(mouseX, mouseY)) { ... }
But to create the rects I also need FontMetrics for their coordinates. So this mean that I have to construct all my rectangles in the paint-method of my menu.
So I want a way to get the FontMetrics so I can construct the Rectangles in a method called by the constructor.
For me the easiest way was to:
Font font = new Font("Helvetica",Font.PLAIN,12);
Canvas c = new Canvas();
FontMetrics fm = c.getFontMetrics(font);
Benefits:
If you call c.getGraphics() it will return null (thus there is no graphics object)
This (canvas) will also work in headless mode.
Now you can easily get height and width...
The really correct answer is to use Toolkit.
Font font = new Font("Courier New", Font.PLAIN, 14);
FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(font);
Once the background component, i.e. whatever is behind your menu, has been rendered, it has a Graphics object that you can use to get the metrics for a given font, just once.
You certainly don't want to be doing this in the paint method, which should be as lightweight as possible. I'd hang this code on a listener that gets called when the component is first rendered. It can store the resulting FontMetrics object somewhere where you can later access it, either in a paint method for drawing those menu item boxes.
Rather than determining the measurements of your menu graphics at the last moment, i.e. when painting, it might be a good idea instead to create some components to represent your menu. You can place those components on the Glass Pane more info here so they'll float above everything else, and you'll have the added bonus that those components are all capable of accepting mouse clicks and firing listener events on them, and since they only capture events on their own geometry you don't even have to figure out which part of menu was hit by the click, if at all.
Another advantage of using components here is that you may entirely get around the requirement for fiddling with font metrics. There are ready-made menu items, or you could just use JLabels, and you can specify their alignment, you can use a LayoutManager to size the boxes to the width of the biggest label, and so forth.
Assuming the menu text is fixed, you could pre-draw the text to a BufferedImage with alpha transparency and make your calculations then. Then, when you need the menu text, just draw the image.
You'll still have to do some offset calculations to centre the image (assuming the panel size can change), but these should be relatively lightweight.
I think this is a good solution
private static HashMap<Font, FontMetrics> fontmetrics = new HashMap<Font, FontMetrics>();
public static FontMetrics getFontMetrics(Font font)
{
if (fontmetrics.containsKey(font))
{
return fontmetrics.get(font);
}
FontMetrics fm = createFontMetrics(font);
fontmetrics.put(font, fm);
return fm;
}
private static FontMetrics createFontMetrics(Font font)
{
BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB_PRE);
Graphics g = bi.getGraphics();
FontMetrics fm = g.getFontMetrics(font);
g.dispose();
bi = null;
return fm;
}
Adding to what Lonzak said, how about this:
public static FontMetrics getFontMetrics(Font font){
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration config = gd.getDefaultConfiguration();
Canvas c = new Canvas(config);
return c.getFontMetrics(font);
}
You could store the 'config' variable as a static variable so it is constructed once in some utility font class that contains other font related information for your game/development environment. I guess you could also do this with the canvas variable.
Updated recommendation. FontMetrics is deprecated. Use LineMetrics instead.
String text = "some string";
FontRenderContext frc = new FontRenderContext(font.getTransform(), true, true);
LineMetrics lm = font.getLineMetrics(text, frc);
However, some methods such as SwingUtilities.computeStringWidth require a FontMetrics instance. Another option is to compute the bounds of the String.
Rectangle2D bounds = font.getStringBounds(text, frc);
Then the width and height may be obtained from the bounds.

Categories