下面列出了java.awt.FontMetrics#charWidth ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void updateDimensionsInHeader() {
StoryFileHeader fileheader = machine.getGameData().getStoryFileHeader();
if (fileheader.getVersion() >= 4) {
FontMetrics fm = imageBuffer.getGraphics().getFontMetrics(fixedFont);
int screenWidth = imageBuffer.getWidth() / fm.charWidth('0');
int screenHeight = imageBuffer.getHeight() / fm.getHeight();
fileheader.setScreenWidth(screenWidth);
fileheader.setScreenHeight(screenHeight);
if (fileheader.getVersion() >= 5) {
fileheader.setScreenWidthUnits(screenWidth);
fileheader.setScreenHeightUnits(screenHeight);
}
}
}
public Dimension getMinimumSize(final int rows, final int columns) {
final Insets insets;
synchronized (getDelegateLock()) {
insets = getTextComponent().getInsets();
}
final int borderHeight = insets.top + insets.bottom;
final int borderWidth = insets.left + insets.right;
final FontMetrics fm = getFontMetrics(getFont());
return new Dimension(fm.charWidth(WIDE_CHAR) * columns + borderWidth,
fm.getHeight() * rows + borderHeight);
}
/**
* Constructor
* @param model data format model that knows how to represent the data
* @param fieldCount number of fields in a row
* @param label label that is used as a renderer in the field viewer
*/
FieldFactory(DataFormatModel model, int bytesPerLine, int fieldOffset, FontMetrics fm,
HighlightProvider highlightProvider) {
this.model = model;
this.fieldOffset = fieldOffset;
this.fm = fm;
this.highlightFactory = new SimpleHighlightFactory(highlightProvider);
charWidth = fm.charWidth('W');
width = charWidth * model.getDataUnitSymbolSize();
editColor = ByteViewerComponentProvider.DEFAULT_EDIT_COLOR;
separatorColor = ByteViewerComponentProvider.DEFAULT_MISSING_VALUE_COLOR;
unitByteSize = model.getUnitByteSize();
}
public Dimension getMinimumSize(final int rows, final int columns) {
final Insets insets;
synchronized (getDelegateLock()) {
insets = getTextComponent().getInsets();
}
final int borderHeight = insets.top + insets.bottom;
final int borderWidth = insets.left + insets.right;
final FontMetrics fm = getFontMetrics(getFont());
return new Dimension(fm.charWidth(WIDE_CHAR) * columns + borderWidth,
fm.getHeight() * rows + borderHeight);
}
public Dimension getMinimumSize(final int rows, final int columns) {
final Insets insets;
synchronized (getDelegateLock()) {
insets = getTextComponent().getInsets();
}
final int borderHeight = insets.top + insets.bottom;
final int borderWidth = insets.left + insets.right;
final FontMetrics fm = getFontMetrics(getFont());
return new Dimension(fm.charWidth(WIDE_CHAR) * columns + borderWidth,
fm.getHeight() * rows + borderHeight);
}
public Dimension getMinimumSize(final int rows, final int columns) {
final Insets insets;
synchronized (getDelegateLock()) {
insets = getTextComponent().getInsets();
}
final int borderHeight = insets.top + insets.bottom;
final int borderWidth = insets.left + insets.right;
final FontMetrics fm = getFontMetrics(getFont());
return new Dimension(fm.charWidth(WIDE_CHAR) * columns + borderWidth,
fm.getHeight() * rows + borderHeight);
}
public static void main(String[] args) throws Exception {
BufferedImage bi = new BufferedImage(1,1,1);
Graphics2D g2d = bi.createGraphics();
Font font = new Font(Font.DIALOG, Font.PLAIN, 12);
if (!font.canDisplay(' ')) {
return;
}
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
if (fm.charWidth(' ') == 0) {
throw new RuntimeException("Space has char width of 0");
}
}
@Override
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column ) {
super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column );
int availableWidth = table.getColumnModel().getColumn( column ).getWidth();
availableWidth -= table.getIntercellSpacing().getWidth();
Insets borderInsets = getBorder().getBorderInsets( (Component)this );
availableWidth -= (borderInsets.left + borderInsets.right);
String cellText = getText();
FontMetrics fm = getFontMetrics( getFont() );
if( fm.stringWidth(cellText) > availableWidth ) {
setToolTipText( value.toString() );
String dots = "..."; //NOI18N
int textWidth = fm.stringWidth( dots );
int nChars = cellText.length() - 1;
for( ; nChars > 0; nChars-- ) {
textWidth += fm.charWidth( cellText.charAt( nChars ) );
if( textWidth > availableWidth ) {
break;
}
}
setText( dots + cellText.substring(nChars + 1) );
} else {
setToolTipText( null );
}
return this;
}
public Dimension getMinimumSize(final int rows, final int columns) {
final Insets insets;
synchronized (getDelegateLock()) {
insets = getTextComponent().getInsets();
}
final int borderHeight = insets.top + insets.bottom;
final int borderWidth = insets.left + insets.right;
final FontMetrics fm = getFontMetrics(getFont());
return new Dimension(fm.charWidth(WIDE_CHAR) * columns + borderWidth,
fm.getHeight() * rows + borderHeight);
}
public Dimension getMinimumSize(final int rows, final int columns) {
final Insets insets;
synchronized (getDelegateLock()) {
insets = getTextComponent().getInsets();
}
final int borderHeight = insets.top + insets.bottom;
final int borderWidth = insets.left + insets.right;
final FontMetrics fm = getFontMetrics(getFont());
return new Dimension(fm.charWidth(WIDE_CHAR) * columns + borderWidth,
fm.getHeight() * rows + borderHeight);
}
/** Computes width of string up to maxCharCount, with font of given JComponent
* and with maximum percentage of owning Window that can be taken */
private static int computeWidth (JComponent comp, int maxCharCount, int percent) {
FontMetrics fm = comp.getFontMetrics(comp.getFont());
int charW = fm.charWidth('X');
int result = charW * maxCharCount;
// limit width to 50% of containing window
Window w = SwingUtilities.windowForComponent(comp);
if (w != null) {
result = Math.min(result, w.getWidth() * percent / 100);
}
return result;
}
public Dimension getMinimumSize(final int rows, final int columns) {
final Insets insets;
synchronized (getDelegateLock()) {
insets = getTextComponent().getInsets();
}
final int borderHeight = insets.top + insets.bottom;
final int borderWidth = insets.left + insets.right;
final FontMetrics fm = getFontMetrics(getFont());
return new Dimension(fm.charWidth(WIDE_CHAR) * columns + borderWidth,
fm.getHeight() * rows + borderHeight);
}
/**
* Return how wide a character is in pixels- must take scale into consideration scale
*
* @param c
* @return character width
*/
public int getCharacterWidth(FontMetrics fontMetrics, SpriteCharacterKey c, ConfigEmoji emojiConfig)
{
if (c.isChar())
{
int baseWidth;
// Extended characters are enabled
if (c.isExtended())
{
if (config.isExtendedCharEnabled())
{
// Return string width of extended char
baseWidth = fontMetrics.charWidth(c.getCodepoint());
// Don't include scale in this calculation, because it's already built into the font size
return (int) (baseWidth + config.getCharSpacing() * config.getFontScale());
}
// The extended character should be replaced with the unknown character
else
{
baseWidth = getCharacterBounds(config.getUnknownChar()).width;
}
}
// It's a normal character
else
{
// Character
baseWidth = getCharacterBounds(c.getCodepoint()).width;
}
return (int) ((baseWidth + config.getCharSpacing()) * config.getFontScale());
}
else
{
// Emoji
int[] eDim = getEmojiDimensions(c, emojiConfig);
final int charSpacing = (int) (config.getCharSpacing() * config.getFontScale());
final int extraSpacing = (c.getEmoji().getType().isBadge() ? Math.max(charSpacing, (int) (BADGE_MINIMUM_SPACING_PIXELS * config.getFontScale())) : charSpacing);
return eDim[0] + extraSpacing;
}
}
public static void main(String args[]) throws Exception {
System.out.println("Default Charset = "
+ Charset.defaultCharset().name());
System.out.println("Locale = " + Locale.getDefault());
String os = System.getProperty("os.name");
String encoding = System.getProperty("file.encoding");
/* Want to test the JA locale uses alternate font for DialogInput. */
boolean jaTest = encoding.equalsIgnoreCase("windows-31j");
if (!os.startsWith("Win") && jaTest) {
System.out.println("Skipping Windows only test");
return;
}
String className = "sun.java2d.SunGraphicsEnvironment";
String methodName = "useAlternateFontforJALocales";
Class sge = Class.forName(className);
Method uafMethod = sge.getMethod(methodName, (Class[])null);
Object ret = uafMethod.invoke(null);
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.preferLocaleFonts();
ge.preferProportionalFonts();
if (jaTest) {
Font msMincho = new Font("MS Mincho", Font.PLAIN, 12);
if (!msMincho.getFamily(Locale.ENGLISH).equals("MS Mincho")) {
System.out.println("MS Mincho not installed. Skipping test");
return;
}
Font dialogInput = new Font("DialogInput", Font.PLAIN, 12);
Font courierNew = new Font("Courier New", Font.PLAIN, 12);
Font msGothic = new Font("MS Gothic", Font.PLAIN, 12);
BufferedImage bi = new BufferedImage(1,1,1);
Graphics2D g2d = bi.createGraphics();
FontMetrics cnMetrics = g2d.getFontMetrics(courierNew);
FontMetrics diMetrics = g2d.getFontMetrics(dialogInput);
FontMetrics mmMetrics = g2d.getFontMetrics(msMincho);
FontMetrics mgMetrics = g2d.getFontMetrics(msGothic);
// This tests to make sure we at least have applied
// "preferLocaleFonts for Japanese
if (cnMetrics.charWidth('A') == diMetrics.charWidth('A')) {
throw new RuntimeException
("Courier New should not be used for DialogInput");
}
// This is supposed to make sure we are using MS Mincho instead
// of MS Gothic. However they are metrics identical so its
// not definite proof.
if (diMetrics.charWidth('A') != mmMetrics.charWidth('A')) {
throw new RuntimeException
("MS Mincho should be used for DialogInput");
}
}
}
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
// setHorizontalAlignment(JLabel.RIGHT); // TODO possibly offer this as an option
int availableWidth = table.getColumnModel().getColumn(column).getWidth();
availableWidth -= table.getIntercellSpacing().getWidth();
Insets borderInsets = getBorder().getBorderInsets((Component)this);
availableWidth -= (borderInsets.left + borderInsets.right);
String cellText = getText();
FontMetrics fm = getFontMetrics( getFont() );
String cellTextReplaced = cellText.replace(Settings.REPLAY_BASE_PATH.get("custom"), "");
if (cellText.equals(cellTextReplaced)) {
if (System.getProperty("os.name").contains("Windows")) {
cellText += "\\";
} else {
cellText += "/";
}
} else {
if (System.getProperty("os.name").contains("Windows")) {
cellText = String.format(".\\%s\\", cellTextReplaced);
} else {
cellText = String.format("./%s/", cellTextReplaced);
}
}
if (fm.stringWidth(cellText) > availableWidth)
{
String dots = "...";
int textWidth = fm.stringWidth( dots );
int nChars = cellText.length() - 1;
for (; nChars > 0; nChars--)
{
textWidth += fm.charWidth(cellText.charAt(nChars));
if (textWidth > availableWidth)
{
break;
}
}
setText(dots + cellText.substring(nChars + 1));
} else {
setText(cellText); // to preserve string replacement
}
return this;
}
public static void main(String args[]) throws Exception {
System.out.println("Default Charset = "
+ Charset.defaultCharset().name());
System.out.println("Locale = " + Locale.getDefault());
String os = System.getProperty("os.name");
String encoding = System.getProperty("file.encoding");
/* Want to test the JA locale uses alternate font for DialogInput. */
boolean jaTest = encoding.equalsIgnoreCase("windows-31j");
if (!os.startsWith("Win") && jaTest) {
System.out.println("Skipping Windows only test");
return;
}
String className = "sun.java2d.SunGraphicsEnvironment";
String methodName = "useAlternateFontforJALocales";
Class sge = Class.forName(className);
Method uafMethod = sge.getMethod(methodName, (Class[])null);
Object ret = uafMethod.invoke(null);
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.preferLocaleFonts();
ge.preferProportionalFonts();
if (jaTest) {
Font msMincho = new Font("MS Mincho", Font.PLAIN, 12);
if (!msMincho.getFamily(Locale.ENGLISH).equals("MS Mincho")) {
System.out.println("MS Mincho not installed. Skipping test");
return;
}
Font dialogInput = new Font("DialogInput", Font.PLAIN, 12);
Font courierNew = new Font("Courier New", Font.PLAIN, 12);
Font msGothic = new Font("MS Gothic", Font.PLAIN, 12);
BufferedImage bi = new BufferedImage(1,1,1);
Graphics2D g2d = bi.createGraphics();
FontMetrics cnMetrics = g2d.getFontMetrics(courierNew);
FontMetrics diMetrics = g2d.getFontMetrics(dialogInput);
FontMetrics mmMetrics = g2d.getFontMetrics(msMincho);
FontMetrics mgMetrics = g2d.getFontMetrics(msGothic);
// This tests to make sure we at least have applied
// "preferLocaleFonts for Japanese
if (cnMetrics.charWidth('A') == diMetrics.charWidth('A')) {
throw new RuntimeException
("Courier New should not be used for DialogInput");
}
// This is supposed to make sure we are using MS Mincho instead
// of MS Gothic. However they are metrics identical so its
// not definite proof.
if (diMetrics.charWidth('A') != mmMetrics.charWidth('A')) {
throw new RuntimeException
("MS Mincho should be used for DialogInput");
}
}
}
public static void main(String args[]) throws Exception {
System.out.println("Default Charset = "
+ Charset.defaultCharset().name());
System.out.println("Locale = " + Locale.getDefault());
String os = System.getProperty("os.name");
String encoding = System.getProperty("file.encoding");
/* Want to test the JA locale uses alternate font for DialogInput. */
boolean jaTest = encoding.equalsIgnoreCase("windows-31j");
if (!os.startsWith("Win") && jaTest) {
System.out.println("Skipping Windows only test");
return;
}
String className = "sun.java2d.SunGraphicsEnvironment";
String methodName = "useAlternateFontforJALocales";
Class sge = Class.forName(className);
Method uafMethod = sge.getMethod(methodName, (Class[])null);
Object ret = uafMethod.invoke(null);
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.preferLocaleFonts();
ge.preferProportionalFonts();
if (jaTest) {
Font msMincho = new Font("MS Mincho", Font.PLAIN, 12);
if (!msMincho.getFamily(Locale.ENGLISH).equals("MS Mincho")) {
System.out.println("MS Mincho not installed. Skipping test");
return;
}
Font dialogInput = new Font("DialogInput", Font.PLAIN, 12);
Font courierNew = new Font("Courier New", Font.PLAIN, 12);
Font msGothic = new Font("MS Gothic", Font.PLAIN, 12);
BufferedImage bi = new BufferedImage(1,1,1);
Graphics2D g2d = bi.createGraphics();
FontMetrics cnMetrics = g2d.getFontMetrics(courierNew);
FontMetrics diMetrics = g2d.getFontMetrics(dialogInput);
FontMetrics mmMetrics = g2d.getFontMetrics(msMincho);
FontMetrics mgMetrics = g2d.getFontMetrics(msGothic);
// This tests to make sure we at least have applied
// "preferLocaleFonts for Japanese
if (cnMetrics.charWidth('A') == diMetrics.charWidth('A')) {
throw new RuntimeException
("Courier New should not be used for DialogInput");
}
// This is supposed to make sure we are using MS Mincho instead
// of MS Gothic. However they are metrics identical so its
// not definite proof.
if (diMetrics.charWidth('A') != mmMetrics.charWidth('A')) {
throw new RuntimeException
("MS Mincho should be used for DialogInput");
}
}
}
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";
}
private void setFontHeightWidth(Font font) {
FontMetrics metrics=getFontMetrics(font);
fontHeight=metrics.getHeight();
charWidth=metrics.charWidth('m');
}
public static void main(String args[]) throws Exception {
System.out.println("Default Charset = "
+ Charset.defaultCharset().name());
System.out.println("Locale = " + Locale.getDefault());
String os = System.getProperty("os.name");
String encoding = System.getProperty("file.encoding");
/* Want to test the JA locale uses alternate font for DialogInput. */
boolean jaTest = encoding.equalsIgnoreCase("windows-31j");
if (!os.startsWith("Win") && jaTest) {
System.out.println("Skipping Windows only test");
return;
}
String className = "sun.java2d.SunGraphicsEnvironment";
String methodName = "useAlternateFontforJALocales";
Class sge = Class.forName(className);
Method uafMethod = sge.getMethod(methodName, (Class[])null);
Object ret = uafMethod.invoke(null);
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.preferLocaleFonts();
ge.preferProportionalFonts();
if (jaTest) {
Font msMincho = new Font("MS Mincho", Font.PLAIN, 12);
if (!msMincho.getFamily(Locale.ENGLISH).equals("MS Mincho")) {
System.out.println("MS Mincho not installed. Skipping test");
return;
}
Font dialogInput = new Font("DialogInput", Font.PLAIN, 12);
Font courierNew = new Font("Courier New", Font.PLAIN, 12);
Font msGothic = new Font("MS Gothic", Font.PLAIN, 12);
BufferedImage bi = new BufferedImage(1,1,1);
Graphics2D g2d = bi.createGraphics();
FontMetrics cnMetrics = g2d.getFontMetrics(courierNew);
FontMetrics diMetrics = g2d.getFontMetrics(dialogInput);
FontMetrics mmMetrics = g2d.getFontMetrics(msMincho);
FontMetrics mgMetrics = g2d.getFontMetrics(msGothic);
// This tests to make sure we at least have applied
// "preferLocaleFonts for Japanese
if (cnMetrics.charWidth('A') == diMetrics.charWidth('A')) {
throw new RuntimeException
("Courier New should not be used for DialogInput");
}
// This is supposed to make sure we are using MS Mincho instead
// of MS Gothic. However they are metrics identical so its
// not definite proof.
if (diMetrics.charWidth('A') != mmMetrics.charWidth('A')) {
throw new RuntimeException
("MS Mincho should be used for DialogInput");
}
}
}