下面列出了java.awt.FontMetrics#getHeight ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public Dimension getPreferredSize(JComponent c) {
int prefHeight = 28;
//Never call getGraphics() on the control, it resets in-process
//painting on OS-X 1.4.1 and triggers gratuitous repaints
Graphics g = BasicScrollingTabDisplayerUI.getOffscreenGraphics();
if (g != null) {
FontMetrics fm = g.getFontMetrics(displayer.getFont());
Insets ins = getTabAreaInsets();
prefHeight = fm.getHeight() + ins.top + ins.bottom + 7;
}
if (prefHeight % 2 == 0) {
prefHeight += 1;
}
return new Dimension(displayer.getWidth(), prefHeight);
}
/**
* Compute height.
*
* @return the int
*/
private int computeHeight()
{
FontMetrics fm = rootPane.getFontMetrics(getFont());
int fontHeight = fm.getHeight();
fontHeight += 7;
int iconHeight = 0;
if (getWindowDecorationStyle() == JRootPane.FRAME)
// ||getWindowDecorationStyle() == JRootPane.PLAIN_DIALOG)//
{
iconHeight = IMAGE_HEIGHT;
}
int finalHeight = Math.max(fontHeight, iconHeight);
return finalHeight+2;//* 改变此处的返回结果将直接改变窗口标题的高度哦
}
protected void measure()
{
final FontMetrics fm = this.getFontMetrics( this.getFont() );
// If we don't have font metrics yet, just return.
if (fm == null) return;
line_height = fm.getHeight();
line_ascent = fm.getAscent();
max_width = 0;
for( int i = 0; i < num_lines; i++ )
{
line_widths[ i ] = fm.stringWidth( lines[ i ] );
if ( line_widths[ i ] > max_width )
max_width = line_widths[i];
}
}
private void drawScaleLine2(Graphics2D g, long breakWidth, long geoBreakWidth) {
FontMetrics metrics = g.getFontMetrics(_font);
float fontHeight = metrics.getHeight();
float leftStart = metrics.stringWidth(String.valueOf(Math.abs(geoBreakWidth))) / 2F;
int yShift = 5;
g.setColor(this.getForeground());
g.setStroke(new BasicStroke(this.lineWidth));
g.draw(new Line2D.Float(leftStart, fontHeight * 1.6f + yShift, leftStart + (breakWidth * _numBreaks), fontHeight * 1.6f + yShift));
g.setFont(this._font);
for (int i = 0; i <= _numBreaks; i++) {
g.draw(new Line2D.Float(leftStart, fontHeight * 1.1f + yShift, leftStart, fontHeight + (fontHeight * 1.1f) + yShift));
g.drawString(String.valueOf(Math.abs(geoBreakWidth * i)),
leftStart - (metrics.stringWidth(String.valueOf(Math.abs(geoBreakWidth * i))) / 2), yShift * _yShiftScale);
leftStart = leftStart + breakWidth;
}
g.drawString(_unitText, leftStart - breakWidth + (fontHeight / 2), fontHeight * 1.1f + yShift * _yShiftScale);
}
/**
* Called when a mouse button is pressed.
*/
public void mousePressed(MouseEvent e) {
Font font = fileWindow.textArea.getFont();
FontMetrics metrics = getFontMetrics(font);
int h = metrics.getHeight();
pressLine = e.getY() / h;
}
private BufferedImage getSplat(int id, int damage)
{
//Get a copy of the hitsplat to get a clean one each time
final BufferedImage rawSplat = spriteManager.getSprite(id, 0);
if (rawSplat == null)
{
return null;
}
final BufferedImage splat = new BufferedImage(
rawSplat.getColorModel(),
rawSplat.copyData(null),
rawSplat.getColorModel().isAlphaPremultiplied(),
null);
final Graphics g = splat.getGraphics();
g.setFont(FontManager.getRunescapeSmallFont());
// Align the text in the centre of the hitsplat
final FontMetrics metrics = g.getFontMetrics();
final String text = String.valueOf(damage);
final int x = (splat.getWidth() - metrics.stringWidth(text)) / 2;
final int y = (splat.getHeight() - metrics.getHeight()) / 2 + metrics.getAscent();
g.setColor(Color.BLACK);
g.drawString(String.valueOf(damage), x + 1, y + 1);
g.setColor(Color.WHITE);
g.drawString(String.valueOf(damage), x, y);
return splat;
}
public void paint(Graphics g, JComponent c) {
FontMetrics metrics = g.getFontMetrics();
Dimension size = c.getSize();
g.setColor(c.getBackground());
g.fillRect(0, 0, size.width, size.height);
g.setColor(c.getForeground());
int y = metrics.getAscent() + 1;
int h = metrics.getHeight();
if(lines != null)
for (int i = 0; i < lines.length; i++) {
g.drawString(lines[i], 3, y);
y += h;
}
}
/**
* Evaluates the preferred size for the TextPane.
*
* @return a Dimension with the preferred TextPane dimensions.
*/
private Dimension calculateTextPaneSize() {
FontMetrics fontMetrics = getFontMetrics(FONT);
int width = fontMetrics.charWidth(' ') * (COLUMNS + 1); // Add a padding column.
int height = fontMetrics.getHeight() * ROWS;
return new Dimension(width, height);
}
double height(Tree<String> tree, FontMetrics fM) {
if (tree == null) {
return 0.0;
}
double depth = tree.getDepth();
// double f = fM.getHeight() ;
return fM.getHeight()
* (depth * (1.0 + parentSkip + aboveLineSkip + belowLineSkip) - parentSkip);
}
/**
* Paints info message about the game.
* @param g2 graphics context in which to paint
*/
private void paintInfo( final Graphics2D g2 ) {
g2.setFont( g2.getFont().deriveFont( Font.BOLD, 22 ) );
final FontMetrics fontMetrics = g2.getFontMetrics();
final int textsCount = 5;
final int lineHeight = fontMetrics.getHeight() << 1;
int y = ( ( Consts.HEIGHT - textsCount * lineHeight ) >> 1 ) + fontMetrics.getAscent();
g2.setColor( Color.LIGHT_GRAY );
for ( int i = 1; i <= textsCount; i++, y += lineHeight ) {
final String text = Language.getText( "mousePracticeGame.info" + i );
g2.drawString( text, ( Consts.WIDTH - fontMetrics.stringWidth( text ) ) >> 1, y );
}
}
/** Measure text
* @param gc AWT Graphics context. Font must be set.
* @param text Text to measure, may be multi-line.
* @return Rectangle where (x, y) is the offset from the top-left
* corner of the text to its baseline as used for gc.drawString(),
* and (width, height) are the overall bounding box.
*/
public static Rectangle measureText(final Graphics2D gc, final String text)
{
final FontMetrics metrics = gc.getFontMetrics();
final Rectangle info = new Rectangle(0, metrics.getLeading() + metrics.getAscent(), 0, 0);
for (String line : text.split("\n"))
{
final int width = metrics.stringWidth(line);
if (width > info.width)
info.width = width;
info.height += metrics.getHeight();
}
return info;
}
/**
* Call this function to determine if the point at x,y is on the unit.
* @param g The graphics context for font size info.
* @param x The x coord.
* @param y The y coord.
* @param w The width of the display.
* @param h The height of the display.
* @return True if the point is on the unit, false otherwise.
*/
public boolean onUnit(Graphics g, int x, int y, int w, int h) {
FontMetrics fm = g.getFontMetrics();
int l = (int)(m_x * w) - fm.stringWidth(m_id) / 2;
int t = (int)(m_y * h) - fm.getHeight() / 2;
if (x < l || x > l + fm.stringWidth(m_id) + 4
|| y < t || y > t + fm.getHeight() + fm.getDescent() + 4) {
return false;
}
return true;
}
private void computeLineY(FontMetrics fm) {
lineY = new int[lineNots.size()];
int curY = 0;
for (int i = 0; i < lineY.length; i++) {
int maxDepth = -1;
ArrayList<NotData> nots = lineNots.get(i);
for (NotData nd : nots) {
if (nd.depth > maxDepth)
maxDepth = nd.depth;
}
lineY[i] = curY + maxDepth * NOT_SEP;
curY = lineY[i] + fm.getHeight() + EXTRA_LEADING;
}
height = Math.max(MINIMUM_HEIGHT, curY - fm.getLeading() - EXTRA_LEADING);
}
private static void drawColumnLabel(Graphics2D graphics, FontMetrics metrics, String text, int yCenter, int[] drawRange, int xRight, boolean updateMin, boolean centeredOnly) {
// If the center is not in the range, don't draw anything
if (drawRange[MAX] < yCenter || drawRange[MIN] > yCenter)
return;
// If there is no space, don't draw anything
if (drawRange[MAX] - drawRange[MIN] < metrics.getHeight())
return;
Java2DStringUtilities.Alignment alignment = Java2DStringUtilities.Alignment.RIGHT;
int targetY = yCenter;
int halfHeight = metrics.getAscent() / 2;
if (yCenter < drawRange[MIN] + halfHeight) {
// Can't be drawn in the center
if (centeredOnly)
return;
alignment = Java2DStringUtilities.Alignment.TOP_RIGHT;
targetY = drawRange[MIN];
} else if (yCenter > drawRange[MAX] - halfHeight) {
// Can't be drawn in the center
if (centeredOnly)
return;
alignment = Java2DStringUtilities.Alignment.BOTTOM_RIGHT;
targetY = drawRange[MAX];
}
Java2DStringUtilities.drawString(graphics, alignment, xRight, targetY, text);
if (updateMin) {
drawRange[MAX] = targetY - metrics.getHeight();
} else {
drawRange[MIN] = targetY + metrics.getHeight();
}
}
/**
* Paints the border for the specified component with the
* specified position and size.
* @param c the component for which this border is being painted
* @param g the paint graphics
* @param x the x position of the painted border
* @param y the y position of the painted border
* @param width the width of the painted border
* @param height the height of the painted border
*/
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
if (!(c instanceof JPopupMenu)) {
return;
}
Font origFont = g.getFont();
Color origColor = g.getColor();
JPopupMenu popup = (JPopupMenu)c;
String title = popup.getLabel();
if (title == null) {
return;
}
g.setFont(font);
FontMetrics fm = SwingUtilities2.getFontMetrics(popup, g, font);
int fontHeight = fm.getHeight();
int descent = fm.getDescent();
int ascent = fm.getAscent();
Point textLoc = new Point();
int stringWidth = SwingUtilities2.stringWidth(popup, fm,
title);
textLoc.y = y + ascent + TEXT_SPACING;
textLoc.x = x + ((width - stringWidth) / 2);
g.setColor(background);
g.fillRect(textLoc.x - TEXT_SPACING, textLoc.y - (fontHeight-descent),
stringWidth + (2 * TEXT_SPACING), fontHeight - descent);
g.setColor(foreground);
SwingUtilities2.drawString(popup, g, title, textLoc.x, textLoc.y);
MotifGraphicsUtils.drawGroove(g, x, textLoc.y + TEXT_SPACING,
width, GROOVE_HEIGHT,
shadowColor, highlightColor);
g.setFont(origFont);
g.setColor(origColor);
}
public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) {
try {
Delegator delegator = (Delegator) request.getAttribute("delegator");
final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"), "default");
final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha", "captcha." + captchaSizeConfigName, delegator);
final String[] captchaSizeConfigs = captchaSizeConfig.split("\\|");
final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), ""); // this is used to uniquely identify in the user session the attribute where the captcha code for the last captcha for the form is stored
final int fontSize = Integer.parseInt(captchaSizeConfigs[0]);
final int height = Integer.parseInt(captchaSizeConfigs[1]);
final int width = Integer.parseInt(captchaSizeConfigs[2]);
final int charsToPrint = UtilProperties.getPropertyAsInteger("captcha", "captcha.code_length", 6);
final char[] availableChars = EntityUtilProperties.getPropertyValue("captcha", "captcha.characters", delegator).toCharArray();
//It is possible to pass the font size, image width and height with the request as well
Color backgroundColor = Color.gray;
Color borderColor = Color.DARK_GRAY;
Color textColor = Color.ORANGE;
Color circleColor = new Color(160, 160, 160);
Font textFont = new Font("Arial", Font.PLAIN, fontSize);
int circlesToDraw = 6;
float horizMargin = 20.0f;
double rotationRange = 0.7; // in radians
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
g.setColor(backgroundColor);
g.fillRect(0, 0, width, height);
//Generating some circles for background noise
g.setColor(circleColor);
for (int i = 0; i < circlesToDraw; i++) {
int circleRadius = (int) (Math.random() * height / 2.0);
int circleX = (int) (Math.random() * width - circleRadius);
int circleY = (int) (Math.random() * height - circleRadius);
g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2);
}
g.setColor(textColor);
g.setFont(textFont);
FontMetrics fontMetrics = g.getFontMetrics();
int maxAdvance = fontMetrics.getMaxAdvance();
int fontHeight = fontMetrics.getHeight();
String captchaCode = RandomStringUtils.random(6, availableChars);
float spaceForLetters = -horizMargin * 2 + width;
float spacePerChar = spaceForLetters / (charsToPrint - 1.0f);
for (int i = 0; i < captchaCode.length(); i++) {
// this is a separate canvas used for the character so that
// we can rotate it independently
int charWidth = fontMetrics.charWidth(captchaCode.charAt(i));
int charDim = Math.max(maxAdvance, fontHeight);
int halfCharDim = (charDim / 2);
BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB);
Graphics2D charGraphics = charImage.createGraphics();
charGraphics.translate(halfCharDim, halfCharDim);
double angle = (Math.random() - 0.5) * rotationRange;
charGraphics.transform(AffineTransform.getRotateInstance(angle));
charGraphics.translate(-halfCharDim, -halfCharDim);
charGraphics.setColor(textColor);
charGraphics.setFont(textFont);
int charX = (int) (0.5 * charDim - 0.5 * charWidth);
charGraphics.drawString("" + captchaCode.charAt(i), charX,
((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent()));
float x = horizMargin + spacePerChar * (i) - charDim / 2.0f;
int y = ((height - charDim) / 2);
g.drawImage(charImage, (int) x, y, charDim, charDim, null, null);
charGraphics.dispose();
}
// Drawing the image border
g.setColor(borderColor);
g.drawRect(0, 0, width - 1, height - 1);
g.dispose();
response.setContentType("image/jpeg");
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
HttpSession session = request.getSession();
Map<String, String> captchaCodeMap = UtilGenerics.checkMap(session.getAttribute("_CAPTCHA_CODE_"));
if (captchaCodeMap == null) {
captchaCodeMap = new HashMap<>();
session.setAttribute("_CAPTCHA_CODE_", captchaCodeMap);
}
captchaCodeMap.put(captchaCodeId, captchaCode);
} catch (IOException | IllegalArgumentException | IllegalStateException ioe) {
Debug.logError(ioe.getMessage(), module);
}
return "success";
}
public int getBaseline(int w, int h) {
FontMetrics fm = getFontMetrics(getFont());
return h - fm.getDescent() - ((h - fm.getHeight()) / 2);
}
/**
* Presents the Exceptions if the chart cannot be displayed properly.
*
* @param g2d
* @param ex
*/
private final void showException( Graphics2D g2d, Exception ex )
{
String sWrappedException = ex.getClass( ).getName( );
Throwable th = ex;
while ( ex.getCause( ) != null )
{
ex = (Exception) ex.getCause( );
}
String sException = ex.getClass( ).getName( );
if ( sWrappedException.equals( sException ) )
{
sWrappedException = null;
}
String sMessage = null;
if ( th instanceof BirtException )
{
sMessage = ( (BirtException) th ).getLocalizedMessage( );
}
else
{
sMessage = ex.getMessage( );
}
if ( sMessage == null )
{
sMessage = "<null>";//$NON-NLS-1$
}
StackTraceElement[] stea = ex.getStackTrace( );
Dimension d = getSize( );
Font fo = new Font( "Monospaced", Font.BOLD, 14 );//$NON-NLS-1$
g2d.setFont( fo );
FontMetrics fm = g2d.getFontMetrics( );
g2d.setColor( Color.WHITE );
g2d.fillRect( 20, 20, d.width - 40, d.height - 40 );
g2d.setColor( Color.BLACK );
g2d.drawRect( 20, 20, d.width - 40, d.height - 40 );
g2d.setClip( 20, 20, d.width - 40, d.height - 40 );
int x = 25, y = 20 + fm.getHeight( );
g2d.drawString( "Exception:", x, y );//$NON-NLS-1$
x += fm.stringWidth( "Exception:" ) + 5;//$NON-NLS-1$
g2d.setColor( Color.RED );
g2d.drawString( sException, x, y );
x = 25;
y += fm.getHeight( );
if ( sWrappedException != null )
{
g2d.setColor( Color.BLACK );
g2d.drawString( "Wrapped In:", x, y );//$NON-NLS-1$
x += fm.stringWidth( "Wrapped In:" ) + 5;//$NON-NLS-1$
g2d.setColor( Color.RED );
g2d.drawString( sWrappedException, x, y );
x = 25;
y += fm.getHeight( );
}
g2d.setColor( Color.BLACK );
y += 10;
g2d.drawString( "Message:", x, y );//$NON-NLS-1$
x += fm.stringWidth( "Message:" ) + 5;//$NON-NLS-1$
g2d.setColor( Color.BLUE );
g2d.drawString( sMessage, x, y );
x = 25;
y += fm.getHeight( );
g2d.setColor( Color.BLACK );
y += 10;
g2d.drawString( "Trace:", x, y );//$NON-NLS-1$
x = 40;
y += fm.getHeight( );
g2d.setColor( Color.GREEN.darker( ) );
for ( int i = 0; i < stea.length; i++ )
{
g2d.drawString( stea[i].getClassName( ) + ":"//$NON-NLS-1$
+ stea[i].getMethodName( ) + "(...):"//$NON-NLS-1$
+ stea[i].getLineNumber( ), x, y );
x = 40;
y += fm.getHeight( );
}
}
double paintTree(Tree<String> t, Point2D start, Graphics2D g2,
FontMetrics fM) {
if (t == null) {
return 0.0;
}
String nodeStr = nodeToString(t);
double nodeWidth = fM.stringWidth(nodeStr);
double nodeHeight = fM.getHeight();
double nodeAscent = fM.getAscent();
WidthResult wr = widthResult(t, fM);
double treeWidth = wr.width;
double nodeTab = wr.nodeTab;
double childTab = wr.childTab;
double nodeCenter = wr.nodeCenter;
// draw root
g2.drawString(nodeStr, (float) (nodeTab + start.getX()),
(float) (start.getY() + nodeAscent));
if (t.isLeaf()) {
return nodeWidth;
}
double layerMultiplier = (1.0 + belowLineSkip + aboveLineSkip + parentSkip);
double layerHeight = nodeHeight * layerMultiplier;
double childStartX = start.getX() + childTab;
double childStartY = start.getY() + layerHeight;
double lineStartX = start.getX() + nodeCenter;
double lineStartY = start.getY() + nodeHeight * (1.0 + belowLineSkip);
double lineEndY = lineStartY + nodeHeight * parentSkip;
// recursively draw children
for (int i = 0; i < t.getChildren().size(); i++) {
Tree<String> child = t.getChildren().get(i);
double cWidth = paintTree(child, new Point2D.Double(childStartX,
childStartY), g2, fM);
// draw connectors
wr = widthResult(child, fM);
double lineEndX = childStartX + wr.nodeCenter;
g2.draw(new Line2D.Double(lineStartX, lineStartY, lineEndX,
lineEndY));
childStartX += cWidth;
if (i < t.getChildren().size() - 1) {
childStartX += sisterSkip * fM.stringWidth(" ");
}
}
return treeWidth;
}
/**
* Returns the bounds for the specified text when it is drawn with the
* left-baseline aligned to the point <code>(x, y)</code>.
*
* @param text the text (<code>null</code> not permitted).
* @param x the x-coordinate.
* @param y the y-coordinate.
* @param fm the font metrics (<code>null</code> not permitted).
*
* @return The bounding rectangle (never <code>null</code>).
*/
public static Rectangle2D getTextBounds(String text, double x, double y,
FontMetrics fm) {
ParamChecks.nullNotPermitted(text, "text");
ParamChecks.nullNotPermitted(fm, "fm");
double width = fm.stringWidth(text);
double height = fm.getHeight();
return new Rectangle2D.Double(x, y - fm.getAscent(), width, height);
}