Comment 40 for bug 289784

Revision history for this message
In , asch (asch) wrote :

The java.awt.font.TextLayout.getBounds() method returns a box that is shifted upwards compared to the box that is returned by Sun's official JRE.

Sample code:
package swingbug;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;

public class SwingBug extends JFrame {

 private static final long serialVersionUID = 1L;

 public static void main(String[] args) {
  new SwingBug().setVisible(true);
 }
 public SwingBug() {
  setTitle("Swing bug");
  setSize(400, 400);
  repaint();
 }
 @Override
 public void paint(Graphics g) {
  Graphics2D graphics=(Graphics2D) g;
  graphics.setColor(Color.BLUE);
  graphics.fillRect(0,0,400,400);
  drawString(graphics, "Hello Kitty!", 100, 100);
 }

 public void drawString(
   Graphics2D graphics, String string, int x, int y) {
  if (string.length() > 0) {
   Font f = new Font("times", 0, 16);
   graphics.setFont(f);
   FontRenderContext fontRendererContext = new FontRenderContext(null, true, true);
   TextLayout textLayout = new TextLayout(string, f, fontRendererContext);
   Rectangle2D rectangleOfText=textLayout.getBounds();
   Rectangle backgroundRectangle=rectangleOfText.getBounds();
   graphics.setColor(new Color(1.0f,1.0f,1.0f,0.5f));
   graphics.fillRect(backgroundRectangle.x+x,backgroundRectangle.y+y,backgroundRectangle.width,backgroundRectangle.height);
   graphics.setColor(new Color(0,0,0));
   textLayout.draw(graphics, x, y);
  }
 }
}