本文整理汇总了Java中java.awt.FontMetrics.charWidth方法的典型用法代码示例。如果您正苦于以下问题:Java FontMetrics.charWidth方法的具体用法?Java FontMetrics.charWidth怎么用?Java FontMetrics.charWidth使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.awt.FontMetrics
的用法示例。
在下文中一共展示了FontMetrics.charWidth方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: setPreferredWidth
import java.awt.FontMetrics; //导入方法依赖的package包/类
/**
* Calculate the width needed to display the maximum line number
*/
private void setPreferredWidth()
{
Element root = component.getDocument().getDefaultRootElement();
int lines = root.getElementCount();
int digits = Math.max(String.valueOf(lines).length(), minimumDisplayDigits);
// Update sizes when number of digits in the line number changes
if (lastDigits != digits)
{
lastDigits = digits;
FontMetrics fontMetrics = getFontMetrics( getFont() );
int width = fontMetrics.charWidth( '0' ) * digits;
Insets insets = getInsets();
int preferredWidth = insets.left + insets.right + width;
Dimension d = getPreferredSize();
d.setSize(preferredWidth, HEIGHT);
setPreferredSize( d );
setSize( d );
}
}
示例2: getFillLevel
import java.awt.FontMetrics; //导入方法依赖的package包/类
private float getFillLevel(char c, FontMetrics f) {
BufferedImage img = new BufferedImage(f.charWidth(c), f.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g = img.createGraphics();
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, antialiasing ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
g.setFont(font);
g.setColor(Color.black);
g.drawString(c+"", 0, img.getHeight()-f.getDescent());
int[] rgb = img.getRGB(0, 0, img.getWidth(), img.getHeight(), null, 0, img.getWidth());
int totalOpacity = 0;
for(int color : rgb)
totalOpacity += ImageTools.getAlpha(color);
return totalOpacity / (float)(rgb.length*255);
}
示例3: KeywordsPanel
import java.awt.FontMetrics; //导入方法依赖的package包/类
/**
* Creates new form KeywordsPanel.
*
* @param view view with the given filter
* @param filter filter to be edited. Can be null and in that case
* all fields are disabled.
*/
public KeywordsPanel( KeywordsFilter filter ) {
this.filter = filter;
initComponents();
initA11y();
if( "Metal".equals( UIManager.getLookAndFeel().getID() ) ) //NOI18N
setOpaque( true );
else
setOpaque( false );
// it's not generated by form editor
JPanel topAlign = new JPanel();
topAlign.setLayout(new BorderLayout());
topAlign.add(conditionsPanel, BorderLayout.NORTH);
conditionsScrollPane.setViewportView(topAlign);
// compute 80x10 chars space in scroll pane
FontMetrics fm = getFontMetrics(getFont());
int width = fm.charWidth('n') * 80; // NOI18N
int height = fm.getHeight() * 10;
conditionsScrollPane.setPreferredSize(new java.awt.Dimension(width, height));
Color background = (Color)UIManager.get("Table.background"); //NOI18N
conditionsPanel.setBackground(background);
topAlign.setBackground(background);
moreButton.addActionListener(this);
fewerButton.addActionListener(this);
matchAllRadio.addActionListener(this);
matchAnyRadio.addActionListener(this);
showFilter(filter);
updateSensitivity();
}
示例4: getFontImage
import java.awt.FontMetrics; //导入方法依赖的package包/类
private BufferedImage getFontImage(final char ch, final boolean antiAlias)
{
final BufferedImage tempfontImage =
new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
final Graphics2D g = (Graphics2D)tempfontImage.getGraphics();
if(antiAlias)
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
else
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
g.setFont(font);
final FontMetrics fontMetrics = g.getFontMetrics();
int charwidth = fontMetrics.charWidth(ch) + 8;
if(charwidth <= 0)
charwidth = 7;
int charheight = fontMetrics.getHeight() + 3;
if(charheight <= 0)
charheight = font.getSize();
final BufferedImage fontImage = new BufferedImage(charwidth, charheight,
BufferedImage.TYPE_INT_ARGB);
final Graphics2D gt = (Graphics2D)fontImage.getGraphics();
if(antiAlias)
gt.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
else
gt.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
gt.setFont(font);
gt.setColor(Color.WHITE);
final int charx = 3;
final int chary = 1;
gt.drawString(String.valueOf(ch), charx,
chary + fontMetrics.getAscent());
return fontImage;
}
示例5: computeWidth
import java.awt.FontMetrics; //导入方法依赖的package包/类
/** 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;
}
示例6: updateCellWidths
import java.awt.FontMetrics; //导入方法依赖的package包/类
/**
* Changes the width of the cells in the JList so you can see every digit
* of each.
*/
void updateCellWidths() {
int oldCellWidth = cellWidth;
cellWidth = getRhsBorderWidth();
// Adjust the amount of space the line numbers take up, if necessary.
if (textArea!=null) {
Font font = getFont();
if (font!=null) {
FontMetrics fontMetrics = getFontMetrics(font);
int count = 0;
int lineCount = textArea.getLineCount() +
getLineNumberingStartIndex() - 1;
do {
lineCount = lineCount/10;
count++;
} while (lineCount >= 10);
cellWidth += fontMetrics.charWidth('9')*(count+1) + 3;
}
}
if (cellWidth!=oldCellWidth) { // Always true
revalidate();
}
}
示例7: getOffsetBeforeX
import java.awt.FontMetrics; //导入方法依赖的package包/类
@Override
public int getOffsetBeforeX(RSyntaxTextArea textArea, TabExpander e,
float startX, float endBeforeX) {
FontMetrics fm = textArea.getFontMetricsForTokenType(getType());
int i = textOffset;
int stop = i + textCount;
float x = startX;
while (i<stop) {
if (text[i]=='\t') {
x = e.nextTabStop(x, 0);
}
else {
x += fm.charWidth(text[i]);
}
if (x>endBeforeX) {
// If not even the first character fits into the space, go
// ahead and say the first char does fit so we don't go into
// an infinite loop.
int intoToken = Math.max(i-textOffset, 1);
return getOffset() + intoToken;
}
i++;
}
// If we got here, the whole token fit in (endBeforeX-startX) pixels.
return getOffset() + textCount - 1;
}
示例8: getMinimumSize
import java.awt.FontMetrics; //导入方法依赖的package包/类
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);
}
示例9: getFontImage
import java.awt.FontMetrics; //导入方法依赖的package包/类
private BufferedImage getFontImage(final char ch, final boolean antiAlias) {
final BufferedImage tempfontImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
final Graphics2D g = (Graphics2D) tempfontImage.getGraphics();
if (antiAlias)
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
else
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
g.setFont(font);
final FontMetrics fontMetrics = g.getFontMetrics();
int charwidth = fontMetrics.charWidth(ch) + 8;
if (charwidth <= 0)
charwidth = 7;
int charheight = fontMetrics.getHeight() + 3;
if (charheight <= 0)
charheight = font.getSize();
final BufferedImage fontImage = new BufferedImage(charwidth, charheight, BufferedImage.TYPE_INT_ARGB);
final Graphics2D gt = (Graphics2D) fontImage.getGraphics();
if (antiAlias)
gt.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
else
gt.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
gt.setFont(font);
gt.setColor(Color.WHITE);
final int charx = 3;
final int chary = 1;
gt.drawString(String.valueOf(ch), charx, chary + fontMetrics.getAscent());
return fontImage;
}
示例10: setFontHeightWidth
import java.awt.FontMetrics; //导入方法依赖的package包/类
private void setFontHeightWidth(Font font) {
FontMetrics metrics=getFontMetrics(font);
fontHeight=metrics.getHeight();
charWidth=metrics.charWidth('m');
}
示例11: render
import java.awt.FontMetrics; //导入方法依赖的package包/类
@Override
public void render(BufferedImage image, String word) {
final int width = image.getWidth();
final int height = image.getHeight();
Graphics2D graphics2D = image.createGraphics();
RenderingHints hints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
hints.add(new RenderingHints(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY));
graphics2D.setRenderingHints(hints);
char[] wordChars = word.toCharArray();
int wordLen = wordChars.length;
Font[] chosenFonts = new Font[wordLen];
int[] charWidths = new int[wordLen];
int widthNeeded = 0;
int maxFontSize = 0;
for (int i = 0; i < wordLen; i++) {
Font font = RandomUtil.rnd(fonts);
if (font.getSize() > maxFontSize) {
maxFontSize = font.getSize();
}
FontMetrics fontMetrics = graphics2D.getFontMetrics(font);
int charWidth = fontMetrics.charWidth(wordChars[i]);
widthNeeded = widthNeeded + charWidth;
chosenFonts[i] = font;
charWidths[i] = charWidth;
}
widthNeeded += charSpace * (wordLen - 1);
int startPosX = (width - widthNeeded) / 2;
int startPosY = (height - maxFontSize) / 5 + maxFontSize;
for (int i = 0; i < wordLen; i++) {
graphics2D.setFont(chosenFonts[i]);
graphics2D.setColor(RandomUtil.rnd(colors));
graphics2D.drawString(String.valueOf(wordChars[i]), startPosX, startPosY);
startPosX = startPosX + charWidths[i] + charSpace;
}
}
示例12: validateWidth
import java.awt.FontMetrics; //导入方法依赖的package包/类
/**
* Helper function used by the block and underline carets to ensure the
* width of the painted caret is valid. This is done for the following
* reasons:
*
* <ul>
* <li>The <code>View</code> classes in the javax.swing.text package
* always return a width of "1" when <code>modelToView</code> is
* called. We'll be needing the actual width.</li>
* <li>Even in smart views, such as <code>RSyntaxTextArea</code>'s
* <code>SyntaxView</code> and <code>WrappedSyntaxView</code> that
* return the width of the current character, if the caret is at the
* end of a line for example, the width returned from
* <code>modelToView</code> will be 0 (as the width of unprintable
* characters such as '\n' is calculated as 0). In this case, we'll
* use a default width value.</li>
* </ul>
*
* @param rect The rectangle returned by the current
* <code>View</code>'s <code>modelToView</code>
* method for the caret position.
*/
private void validateWidth(Rectangle rect) {
// If the width value > 1, we assume the View is
// a "smart" view that returned the proper width.
// So only worry about this stuff if width <= 1.
if (rect!=null && rect.width<=1) {
// The width is either 1 (most likely, we're using a "dumb" view
// like those in javax.swing.text) or 0 (most likely, we're using
// a "smart" view like org.fife.ui.rsyntaxtextarea.SyntaxView,
// we're at the end of a line, and the width of '\n' is being
// computed as 0).
try {
// Try to get a width for the character at the caret
// position. We use the text area's font instead of g's
// because g's may vary in an RSyntaxTextArea.
RTextArea textArea = getTextArea();
textArea.getDocument().getText(getDot(),1, seg);
Font font = textArea.getFont();
FontMetrics fm = textArea.getFontMetrics(font);
rect.width = fm.charWidth(seg.array[seg.offset]);
// This width being returned 0 likely means that it is an
// unprintable character (which is almost 100% to be a
// newline char, i.e., we're at the end of a line). So,
// just use the width of a space.
if (rect.width==0) {
rect.width = fm.charWidth(' ');
}
} catch (BadLocationException ble) {
// This shouldn't ever happen.
ble.printStackTrace();
rect.width = 8;
}
} // End of if (rect!=null && rect.width<=1).
}
示例13: listOffsetToView
import java.awt.FontMetrics; //导入方法依赖的package包/类
@Override
public Rectangle listOffsetToView(RSyntaxTextArea textArea, TabExpander e,
int pos, int x0, Rectangle rect) {
int stableX = x0; // Cached ending x-coord. of last tab or token.
TokenImpl token = this;
FontMetrics fm = null;
Segment s = new Segment();
while (token != null && token.isPaintable()) {
fm = textArea.getFontMetricsForTokenType(token.getType());
if (fm == null) {
return rect; // Don't return null as things'll error.
}
char[] text = token.text;
int start = token.textOffset;
int end = start + token.textCount;
// If this token contains the position for which to get the
// bounding box...
if (token.containsPosition(pos)) {
s.array = token.text;
s.offset = token.textOffset;
s.count = pos - token.getOffset();
// Must use this (actually fm.charWidth()), and not
// fm.charsWidth() for returned value to match up with where
// text is actually painted on OS X!
int w = Utilities.getTabbedTextWidth(s, fm, stableX, e,
token.getOffset());
rect.x = stableX + w;
end = token.documentToToken(pos);
if (text[end] == '\t') {
rect.width = fm.charWidth(' ');
}
else {
rect.width = fm.charWidth(text[end]);
}
return rect;
}
// If this token does not contain the position for which to get
// the bounding box...
else {
s.array = token.text;
s.offset = token.textOffset;
s.count = token.textCount;
stableX += Utilities.getTabbedTextWidth(s, fm, stableX, e,
token.getOffset());
}
token = (TokenImpl)token.getNextToken();
}
// If we didn't find anything, we're at the end of the line. Return
// a width of 1 (so selection highlights don't extend way past line's
// text). A ConfigurableCaret will know to paint itself with a larger
// width.
rect.x = stableX;
rect.width = 1;
return rect;
}
示例14: main
import java.awt.FontMetrics; //导入方法依赖的package包/类
public static void main(String[] args) {
List<String> monospaceFontFamilyNames = new ArrayList<>();
GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment
.getLocalGraphicsEnvironment();
String[] fontFamilyNames = graphicsEnvironment
.getAvailableFontFamilyNames();
BufferedImage bufferedImage = new BufferedImage(1, 1,
BufferedImage.TYPE_INT_ARGB);
Graphics graphics = bufferedImage.createGraphics();
for (String fontFamilyName : fontFamilyNames) {
boolean isMonospaced = true;
//
int fontStyle = Font.PLAIN;
int fontSize = 12;
Font font = new Font(fontFamilyName, fontStyle, fontSize);
@SuppressWarnings("serial")
List<Integer> codePoints = new ArrayList<Integer>() {
{
add(108); /* l */
add(109); /* m */
add(119); /* w */
add(49); /* 1 */
add(52); /* 4 */
}
};
FontMetrics fontMetrics = graphics.getFontMetrics(font);
int firstCharacterWidth = 0;
boolean hasFirstCharacterWidth = false;
for (int codePoint : codePoints) {
if (Character.isValidCodePoint(codePoint)
&& (Character.isLetter(codePoint)
|| Character.isDigit(codePoint))) {
char character = (char) codePoint;
int characterWidth = fontMetrics.charWidth(character);
if (hasFirstCharacterWidth) {
if (characterWidth != firstCharacterWidth) {
isMonospaced = false;
break;
}
} else {
firstCharacterWidth = characterWidth;
hasFirstCharacterWidth = true;
}
}
}
if (isMonospaced) {
monospaceFontFamilyNames.add(fontFamilyName);
}
}
graphics.dispose();
for (String fontFamily : monospaceFontFamilyNames) {
System.out.println(fontFamily);
}
}
示例15: main
import java.awt.FontMetrics; //导入方法依赖的package包/类
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");
}
}
}