我只想在一个充满黑色的矩形中显示我的String。谢谢你的帮助!
答案 0 :(得分:8)
你在这里:
public class MyPanel extends JPanel{
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(10/*x*/, 10/*y*/, 80/*width*/, 30/*hight*/);
g.drawString("TextToDraw", 25/*x*/, 25/*y*/);
}
}
答案 1 :(得分:2)
public class LabeledRectangle extends Rectangle{
public LabeledRectangle(int x, int y, int width, int height, String text) {
super (x, y, width, height);
this.text = text;
}
public void draw(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.draw(new Rectangle2D.Double(x, y, width,height));
Font font = g2.getFont();
FontRenderContext context = g2.getFontRenderContext();
g2.setFont(font);
int textWidth = (int) font.getStringBounds(text, context).getWidth();
LineMetrics ln = font.getLineMetrics(text, context);
int textHeight = (int) (ln.getAscent() + ln.getDescent());
int x1 = x + (width - textWidth)/2;
int y1 = (int)(y + (height + textHeight)/2 - ln.getDescent());
g2.setColor(Color.red);
g2.drawString(text, (int) x1, (int) y1);
}
private String text;
}