/*
* TextRectDemo.java
*/
package text;
import java.awt.*;
import javax.swing.*;
public class TextRectDemo extends JFrame {
private Text text;
public TextRectDemo() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400,300);
text = new Text();
add(text);
}
public static void main(final String args[]) {new TextRectDemo().setVisible(true);}
}
class Text extends JPanel{
private String text = "Hallo Welt";
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D graphics2D = (Graphics2D) g;
Window window = SwingUtilities.getWindowAncestor(this);
Rectangle viewRect = window.getBounds();
Font font = graphics2D.getFont().deriveFont(30f);
graphics2D.setFont(font);
Rectangle textRect = new Rectangle();
text = SwingUtilities.layoutCompoundLabel(this,
graphics2D.getFontMetrics(), text, null,
SwingConstants.TOP, SwingConstants.CENTER,
SwingConstants.CENTER, SwingConstants.CENTER,
viewRect, new Rectangle(), textRect, 0);
graphics2D.drawString(text, textRect.x, textRect.y+textRect.height);
graphics2D.drawRect(textRect.x, textRect.y, textRect.width, textRect.height);
}
}