FontMetrics returns wrong height - java

I want to get the exact height of my string in pixels on my panel. So I wrote a program that draws the string, and then draws a rectangle around it.
Using FontMetrics I used the getStringBounds method to get me the enclosing rectangle.
However it looks wrong :
I was expecting the rectangle to perfectly enclose my text, but there is space at the top (And a tiny bit of space on the left and right). Why is it giving me this result?
Here is my code :
public class Test extends JPanel {
#Override
protected void paintComponent(Graphics g) {
Font font = new Font("Arial", Font.PLAIN, 60);
g.setFont(font);
FontMetrics fm = this.getFontMetrics(font);
String str = "100dhgt";
Rectangle2D rect = fm.getStringBounds(str, g);
int x = 5;
int y = 100;
g.drawRect(x, y - (int)rect.getHeight(), (int)rect.getWidth(), (int)rect.getHeight());
g.drawString(str, x, y);
}
public static void main(String[] args) {
JFrame f = new JFrame();
Test test = new Test();
f.add(test);
f.setVisible(true);
f.setSize(400, 400);
}
}

Regarding your rectangle, you have to consider the font's descend (how far is it below the line)
g.drawString(str, x, y - fm.getDescent());
Also note that the font height usually considers some kind of line spacing. In this case fm.getDescent() + fm.getAscent() = 68 whereas fm.getHeight() = 70

The space at the top can be explained by your not taking account of the descent (which takes me back to one of my favorite methods from java 1.0: getMaxDecent)
Otherwise, the box looks pretty good. The only other advice I can offer is that fm.getStringBounds works better with some fonts than it does with others

Related

Java - Centering Text (on a Canvas)

thanks for checking out my question.
I am working a menu for the game that I'm making, and I want to center the game's title on the main menu. I've looked at several questions here on Stack Overflow, but couldn't find an answer.
Problem
The problem that I'm having is that whenever I call my centerString() method, it puts it in the center of the y-axis, but not of the x-axis. What am I doing wrong here?
Code
Method code
private void centerString(String txt, int width, int height, Graphics g, Font font) {
FontMetrics metrics = g.getFontMetrics();
int x = (width - metrics.stringWidth(txt)) / 2;
int y = (metrics.getAscent() + (height - (metrics.getAscent() + metrics.getDescent())) / 2);
g.setFont(font);
g.drawString(txt, x, y);
}
Where it's called
final Font fnt = new Font("Arial", Font.BOLD, 36);
centerString("ThatMarioEngine", toInt(screenSize.getWidth()), toInt(screenSize.getHeight()), g, fnt);
I have fixed the issue by making using the windows size, instead of the screen size. The centering issue was fixed by putting g.setFont(font); before I get the FontMetrics.

My Java polygon is not drawing, despite having seemingly valid vertex coordinates

My teacher is having us write code to draw a logo on the screen using awt, swing, and the graphics class. I decided to draw the google drive symbol, but I am getting stuck on the yellow third.
public class DriveLogo extends JApplet
{
public void init()
{
JRootPane rootPane = this.getRootPane();
rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
}
public void paint(Graphics g)
{
int num_rect_points = 4;
g.setColor(Color.black);
g.fillRect(0,0,getSize().width, getSize().height);
/*************************************Yellow 1/3**********************************/
//Order of vertices: Left, right, lower-right, lower-left
int p1x1 = 150, p1x2 = 250, p1x3 = 350, p1x4 = 300;
int p1y1 = 25, p1y2 = 25, p1y3 = 280, p1y4 = 280;
int[] poly_1_x = {
p1x1, p1x2, p1x3, p1x4
};
int[] poly_1_y = {
p1y1, p1y2, p1y3, p1y4
};
Polygon yellow = new Polygon(poly_1_x, poly_1_y, num_rect_points);
/*************************************Draw**********************************/
g.setColor(Color.yellow);
g.fillPolygon(yellow);
}
}
This produces the following result:
There should be a yellow rhombus/rectangle slanted to the left. I asked my teacher, and she reviewed my code, but could not isolate the problem, and told me it "should" be working. Should doesn't mean it is however, and this is a rather large grade. Spent most of two class periods and downloaded the project to my home computer to debug, but I just can't seem to figure out what the problem is.
Things I know; the polygon coordinates must be in order, so to draw a rectangle, I cannot list them top-left, bottom-right, bottom-left, top-right, but I can list them top-left, top-right, bottom-right, bottom-left.
Okay, I solved this by experimenting around. For whatever reason, the call to g.fillPolygon(Polygon p) was not working, but when I called g.fillPolygon(poly_1_x, poly_1_y, num_recto_points); it worked properly.

How can I map a custom image to a polygon in a game? [duplicate]

This question already has answers here:
Adding Image to a Polygon
(2 answers)
Closed 8 years ago.
I'm trying to basically remake Asteroids in java, but I'm going to use a bald eagle as a ship that shoots down Soviet flags. Right now, my bald eagle image is a square with a white outline around the eagle. I would like to remove this, is there any way to map this in a one-to-one fashion to a polygon of sorts?
Here's my code, though I don't know exactly how this will help anything:
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
GameTest t = new GameTest();
}
public static class GameTest extends JFrame {
private static final int WINDOW_WIDTH = 800;
private static final int WINDOW_HEIGHT = 500;
private GamePanel gamePanel;
public GameTest() throws IOException {
super("Deep Fried Freedom");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setLayout(new BorderLayout());
gamePanel = new GamePanel();
add(gamePanel);
center(this);
setVisible(true);
}
public static void center(JFrame frame) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Point center = ge.getCenterPoint();
int w = frame.getWidth();
int h = frame.getHeight();
int x = center.x - w / 2, y = center.y - h / 2;
frame.setBounds(x, y, w, h);
frame.validate();
}//end of center method
}
}
public class GamePanel extends JPanel {
public static BufferedImage baldEagleImage;
public GamePanel() throws IOException {
super();
baldEagleImage = ImageIO.read(new File("baldeagleimage.jpg"));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);// set color black
g.fillRect(0, 0, getWidth(), getHeight()); // paint background
g.drawImage(baldEagleImage, 350, 175, null);//paint the launcher
}//end paintComponent method
}//end GamePanel class
You have several ways that you can achieve this effect. Your best bet would be to use the alpha channel of your image. Just open your image in an image editing tool such as Gimp. In this set the background of your image to transparent around your image.
Another option (which is not the best) but fulfils your request is to use a paint stroke in Java2D. Have a look at using the java2d clipping feature. You can get a tutorial on this here
Usually you will have a Java object that represents the ship, and it has x and y coordinates called something like centerX and centerY. That gives you the center of the ship on your screen within the bounds of the viewable area. You modify these values when you want the ship to move up and down, and you g.drawImage the image you want to use at these coordinates as well (plus any offsets as needed to make the image appear centered to your liking).
A common method is to have a thread started upon initialization, and in that thread is a while(true) block that does an update() method on all objects that need to be updated, and then a Thread.sleep(17) that mimics a framerate of about 60 frames per second. In this method, your ship has its X and Y coords updated and then the image drawn at that location every 17 milliseconds, and that's how you get a ship (and any other object for that matter) to appear like they are moving around on the screen.

x-y plot and rotating text of axis-label

The code below plots some simple x-y data, but it has two problems that I do not know how to fix.
First, it plots negative values for some of the data points, which means lines extending southward below the x-axis. Since the data points are selected at random, you may have to resize the frame a bit in order to view new random numbers to be plotted in a way that shows this bug. All data values will be positive, so I want all deflections to project northward above the blue bottom marker line, and I need to make sure that no deflections extend southward below the blue bottom marker line.
Second, the y-axis label takes up too much real estate on the screen. It needs to be rotated -90 degrees. However, all the examples I have seen for this involve rotating the entire panel using a graphics2d object. I do not want to rotate the entire panel. Instead, I just want to rotate the text of the y-axis label.
Can anyone show me how to change the code below to fix these two specific problems?
The code is in the following two files:
GUI.java
import java.awt.*;
import javax.swing.*;
class GUI{
GUI() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("X-Y Plot");
// Specify FlowLayout for the layout manager.
jfrm.getContentPane().setLayout(new FlowLayout());
int frameHeight = 400;
int frameWidth = 300;
// Give the frame an initial size.
jfrm.setSize(frameWidth, frameHeight);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a text-based label.
JVertLabel myVLabel = new JVertLabel("y-axis label");
int width = myVLabel.WIDTH;
PaintPanel myPP = new PaintPanel(frameWidth-width-50-20,frameHeight-70);
jfrm.add(myPP);
jfrm.add(myVLabel);// Add the label to the frame.
// Display the frame.
jfrm.setVisible(true);
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {public void run(){new GUI();}});
}
public class JVertLabel extends JComponent {
private String text;
public JVertLabel(String s) {
text = s;
}//constructor
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.rotate(Math.toRadians(-90));
g2d.drawString(text, 0, 0);
}
}
}
PaintPanel.java
import java.awt.*;
import javax.swing.*;
import java.util.*;
class PaintPanel extends JPanel {
Insets ins; // holds the panel's insets
Random rand; // used to generate random numbers
PaintPanel(int w, int h) {
setOpaque(true);// Ensure that panel is opaque.
setPreferredSize(new Dimension(w, h));// Set preferred dimension as specfied.
rand = new Random();
}
protected void paintComponent(Graphics g) {// Override paintComponent() method.
super.paintComponent(g);// Always call superclass method first.
int height = getHeight();// Get height of component.
int width = getWidth();// Get width of component.
ins = getInsets();// Get the insets.
// Get dimensions of text
Graphics2D g2d = (Graphics2D) g;
Font font = new Font("Serif", Font.PLAIN, 12);
FontMetrics fontMetrics = g2d.getFontMetrics();
String xString = ("x-axis label");
int xStrWidth = fontMetrics.stringWidth(xString);
int xStrHeight = fontMetrics.getHeight();
String yString = "y-axis-label";
int yStrWidth = fontMetrics.stringWidth(yString);
int yStrHeight = fontMetrics.getHeight();
int leftStartPlotWindow = ins.left + 5 + yStrWidth;
int hPad = 3;
// Fill panel by plotting random data in a bar graph.
for (int i = leftStartPlotWindow + hPad; i <= width - leftStartPlotWindow - hPad + yStrWidth + 1; i += 4) {
int h = Math.abs(rand.nextInt(height - ins.bottom));//Get rand# betw/0 and max height of drawing area.
// If generated value w/in or too close to border, change it to just outside border.
if (h <= ins.top) {
h = ins.top + 1;
}
g.drawLine(i, Math.abs(height - ins.bottom - xStrHeight - 5), i, h);// Draw a line that represents data.
}
g.setColor(Color.blue);
g.drawRect(leftStartPlotWindow, ins.bottom + 2, width - leftStartPlotWindow - ins.right - hPad, height - xStrHeight - 6);
g.setColor(Color.red);
g.drawRect(ins.left, ins.bottom, width - ins.left - 1, height - ins.bottom - 1);
g.drawString(xString, (width / 2) - (xStrWidth / 2), height - ins.bottom - 6);
g.drawString(yString, ins.left, height / 2);
}
}
All data values will be positive, so I want all deflections to project northward above the blue bottom marker line, and I need to make sure that no deflections extend southward below the blue bottom marker line.
You need to calculate the random height so that all values fit into the space available. So the calculation would be something like:
int randomHeight = panelHeight - offset.top - offset.bottom - heightForTheXAxisText;
Then you don't have to worry about negative values or the top of the line extending outside the bounds of the panel.
all the examples I have seen for this involve rotating the entire panel using a graphics2d object. I do not want to rotate the entire panel. Instead, I just want to rotate the text of the y-axis label.
Set the rotation of the Graphics object, the draw the text, then restore the rotation of the Graphics object back to 0.
Or, you create create a new Graphcis object from the current Graphics object, then apply the rotation, draw the text and then dispose of the temporaray Graphics object.
JFreeChart addresses both issues by default, as shown in this example.
In your example,
You'll have to create the data model before trying to render it. Then you can scan it for min and max to determine the limits of your range axis. List<Double> may be a suitable choice.
You can rotate the range label by altering the graphics context's AffineTransform, as shown in RotateText.

Java monospace draw string

How can I draw a String in Java (using Graphics2d) in monospace mode? I have a font that looks like LCD screen font, and I want to draw something like LCD label.
I am using Digital 7 Mono font.
Do you know where I can find another font that will be monospace and lcd (I wan to type only digitals)?
How can I draw a String in Java (using Graphics2d) in monospace mode?
The essential method needed to render text is drawString(), as outlined below. There is no "monospace mode", per se, but even proportionally spaced fonts typically use a constant width for digit glyphs .
private static final Font font = new Font("Monospaced", Font.PLAIN, 32);
private static final String s = "12:34";
...
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(font);
int xx = this.getWidth();
int yy = this.getHeight();
int w2 = g.getFontMetrics().stringWidth(s) / 2;
int h2 = g.getFontMetrics().getDescent();
g.setColor(Color.green);
g.drawString(s, xx / 2 - w2, yy / 2 + h2);
}
There's a complete example here, and you can extend a suitable JComponent to control positioning using a layout manager, as seen here.

Categories

Resources