public void paint(Graphics g) { m_fm = g.getFontMetrics(); g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); getBorder().paintBorder(this, g, 0, 0, getWidth(), getHeight()); g.setColor(getForeground()); g.setFont(getFont()); m_insets = getInsets(); int x = m_insets.left; int y = m_insets.top + m_fm.getAscent(); StringTokenizer st = new StringTokenizer(getText(), "\t"); while (st.hasMoreTokens()) { String sNext = st.nextToken(); g.drawString(sNext, x, y); x += m_fm.stringWidth(sNext); if (!st.hasMoreTokens()) break; int index = 0; while (x >= getTab(index)) index++; x = getTab(index); } }
/** * This is called to paint within the EditCanvas * * @param g Graphics * @param c DisplayCanvas to paint on. */ public void paint(Graphics g, DisplayCanvas c) { Rectangle nb = transformOutput(c, getBounds()); if (!getActive()) { Rectangle r = getBounds(); g.setColor(Color.lightGray); g.fillRect(r.x, r.y, r.width, r.height); } draw((Graphics2D) g, nb.x, nb.y, nb.width, nb.height); if ((c instanceof StationModelCanvas) && ((StationModelCanvas) c).getShowParams()) { int xoff = 0; FontMetrics fm = g.getFontMetrics(); g.setColor(Color.black); for (int i = 0; i < paramIds.length; i++) { String s = paramIds[i]; if (i > 0) { s = ", " + s; } g.drawString(s, nb.x + xoff, nb.y + nb.height + fm.getMaxDescent() + fm.getMaxAscent() + 4); xoff += fm.stringWidth(s); } } if ((c instanceof StationModelCanvas) && ((StationModelCanvas) c).shouldShowAlignmentPoints()) { paintRectPoint(g, c); } }
void setPosition(int newX, int newY) { Insets insets = eNode.getContext().getInsets(); FontMetrics metrics = getFontMetrics(getFont()); int stringWidth = metrics.stringWidth(getText()); int stringHeight = metrics.getHeight(); setBounds( newX + insets.left + eNode.getWidth() + SEPARATION, newY + insets.top + eNode.getInsets().top, metrics.stringWidth(getText()), metrics.getHeight()); }
/** * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public int getBaseline(JComponent c, int width, int height) { super.getBaseline(c, width, height); if (progressBar.isStringPainted() && progressBar.getOrientation() == JProgressBar.HORIZONTAL) { FontMetrics metrics = progressBar.getFontMetrics(progressBar.getFont()); Insets insets = progressBar.getInsets(); int y = insets.top; height = height - insets.top - insets.bottom; return y + (height + metrics.getAscent() - metrics.getLeading() - metrics.getDescent()) / 2; } return -1; }
void setPosition(int newX, int newY) { Insets insets = getContext().getInsets(); insets = getContext().getInsets(); FontMetrics metrics = getFontMetrics(getFont()); int stringWidth = metrics.stringWidth(getText()); int stringHeight = metrics.getHeight(); setBounds( newX + insets.left, newY + insets.top, stringWidth + getInsets().left + getInsets().right, stringHeight + insets.top + insets.bottom + VERTICAL_PAD); if (rightLabel != null) rightLabel.setPosition(newX, newY); }
private Dimension calcTypeListPreferredSize(final List<ModuleBuilder> allModuleTypes) { int width = 0; int height = 0; final FontMetrics fontMetrics = myTypesList.getFontMetrics(myTypesList.getFont()); final int fontHeight = fontMetrics.getMaxAscent() + fontMetrics.getMaxDescent(); for (final ModuleBuilder type : allModuleTypes) { final Icon icon = type.getBigIcon(); final int iconHeight = icon != null ? icon.getIconHeight() : 0; final int iconWidth = icon != null ? icon.getIconWidth() : 0; height += Math.max(iconHeight, fontHeight) + 6; width = Math.max(width, iconWidth + fontMetrics.stringWidth(type.getPresentableName()) + 10); } return new Dimension(width, height); }
/** * Determines the preferred span for this view along an axis. * * @param axis may be either View.X_AXIS or View.Y_AXIS * @return the span the view would like to be rendered into >= 0. Typically the view is told to * render into the span that is returned, although there is no guarantee. The parent may * choose to resize or break the view. * @exception IllegalArgumentException for an invalid axis */ @Override public float getPreferredSpan(int axis) { updateMetrics(); switch (axis) { case View.X_AXIS: float span = longLineWidth + getRhsCorrection(); // fudge factor if (host.getEOLMarkersVisible()) { span += metrics.charWidth('\u00B6'); } return span; case View.Y_AXIS: // We update lineHeight here as when this method is first // called, lineHeight isn't initialized. If we don't do it // here, we get no vertical scrollbar (as lineHeight==0). lineHeight = host != null ? host.getLineHeight() : lineHeight; // return getElement().getElementCount() * lineHeight; int visibleLineCount = getElement().getElementCount(); if (host.isCodeFoldingEnabled()) { visibleLineCount -= host.getFoldManager().getHiddenLineCount(); } return visibleLineCount * (float) lineHeight; default: throw new IllegalArgumentException("Invalid axis: " + axis); } }
public Dimension getPreferredSize(JComponent c) { Dimension size; Insets border = progressBar.getInsets(); FontMetrics fontSizer = progressBar.getFontMetrics(progressBar.getFont()); if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) { size = new Dimension(getPreferredInnerHorizontal()); // Ensure that the progress string will fit if (progressBar.isStringPainted()) { // I'm doing this for completeness. String progString = progressBar.getString(); int stringWidth = SwingUtilities2.stringWidth(progressBar, fontSizer, progString); if (stringWidth > size.width) { size.width = stringWidth; } // This uses both Height and Descent to be sure that // there is more than enough room in the progress bar // for everything. // This does have a strange dependency on // getStringPlacememnt() in a funny way. int stringHeight = fontSizer.getHeight() + fontSizer.getDescent(); if (stringHeight > size.height) { size.height = stringHeight; } } } else { size = new Dimension(getPreferredInnerVertical()); // Ensure that the progress string will fit. if (progressBar.isStringPainted()) { String progString = progressBar.getString(); int stringHeight = fontSizer.getHeight() + fontSizer.getDescent(); if (stringHeight > size.width) { size.width = stringHeight; } // This is also for completeness. int stringWidth = SwingUtilities2.stringWidth(progressBar, fontSizer, progString); if (stringWidth > size.height) { size.height = stringWidth; } } } size.width += border.left + border.right; size.height += border.top + border.bottom; return size; }
/** * Determines the minimum span for this view along an axis. This is implemented to provide the * superclass behavior after first making sure that the current font metrics are cached (for the * nested lines which use the metrics to determine the height of the potentially wrapped lines). * * @param axis may be either View.X_AXIS or View.Y_AXIS * @return the span the view would like to be rendered into. Typically the view is told to render * into the span that is returned, although there is no guarantee. The parent may choose to * resize or break the view. * @see View#getMinimumSpan */ public float getMinimumSpan(int axis) { updateMetrics(); float span = super.getPreferredSpan(axis); if (axis == View.X_AXIS) { // EOL marker span += metrics.charWidth('\u00b6'); // metrics set in updateMetrics } return span; }
/* * Determine the Y offset for the current row */ private int getOffsetY(int rowStartOffset, FontMetrics fontMetrics) throws BadLocationException { // Get the bounding rectangle of the row Rectangle r = component.modelToView(rowStartOffset); int lineHeight = fontMetrics.getHeight(); int y = r.y + r.height; int descent = 0; // The text needs to be positioned above the bottom of the bounding // rectangle based on the descent of the font(s) contained on the row. if (r.height == lineHeight) { // default font is being used descent = fontMetrics.getDescent(); } else { // We need to check all the attributes for font changes if (fonts == null) { fonts = new HashMap<String, FontMetrics>(); } Element root = component.getDocument().getDefaultRootElement(); int index = root.getElementIndex(rowStartOffset); Element line = root.getElement(index); for (int i = 0; i < line.getElementCount(); i++) { Element child = line.getElement(i); AttributeSet as = child.getAttributes(); String fontFamily = (String) as.getAttribute(StyleConstants.FontFamily); Integer fontSize = (Integer) as.getAttribute(StyleConstants.FontSize); String key = fontFamily + fontSize; FontMetrics fm = fonts.get(key); if (fm == null) { Font font = new Font(fontFamily, Font.PLAIN, fontSize); fm = component.getFontMetrics(font); fonts.put(key, fm); } descent = Math.max(descent, fm.getDescent()); } } return y - descent; }
/** 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); } }
/** * Draw the line numbers * * @param g */ @Override public void paintComponent(Graphics g) { super.paintComponent(g); ((Graphics2D) g) .setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Determine the width of the space available to draw the line number FontMetrics fontMetrics = component.getFontMetrics(component.getFont()); Insets insets = getInsets(); int availableWidth = getSize().width - insets.left - insets.right; // Determine the rows to draw within the clipped bounds. Rectangle clip = g.getClipBounds(); int rowStartOffset = component.viewToModel(new Point(0, clip.y)); int endOffset = component.viewToModel(new Point(0, clip.y + clip.height)); while (rowStartOffset <= endOffset) { try { if (isCurrentLine(rowStartOffset)) g.setColor(getCurrentLineForeground()); else g.setColor(getForeground()); // Get the line number as a string and then determine the // "X" and "Y" offsets for drawing the string. String lineNumber = getTextLineNumber(rowStartOffset); int stringWidth = fontMetrics.stringWidth(lineNumber); int x = getOffsetX(availableWidth, stringWidth) + insets.left; int y = getOffsetY(rowStartOffset, fontMetrics); g.drawString(lineNumber, x, y); // Move to the next row rowStartOffset = Utilities.getRowEnd(component, rowStartOffset) + 1; } catch (Exception e) { break; } } }
/** * Iterate over the lines represented by the child elements of the element this view represents, * looking for the line that is the longest. The <em>longLine</em> variable is updated to * represent the longest line contained. The <em>font</em> variable is updated to indicate the * font used to calculate the longest line. */ void calculateLongestLine() { Component c = getContainer(); font = c.getFont(); metrics = c.getFontMetrics(font); tabSize = getTabSize() * metrics.charWidth(' '); Element lines = getElement(); int n = lines.getElementCount(); for (int i = 0; i < n; i++) { Element line = lines.getElement(i); float w = getLineWidth(i); if (w > longLineWidth) { longLineWidth = w; longLine = line; } } }
/** * Designate the place where the progress string will be painted. This implementation places it at * the center of the progress bar (in both x and y). Override this if you want to right, left, * top, or bottom align the progress string or if you need to nudge it around for any reason. */ protected Point getStringPlacement( Graphics g, String progressString, int x, int y, int width, int height) { FontMetrics fontSizer = SwingUtilities2.getFontMetrics(progressBar, g, progressBar.getFont()); int stringWidth = SwingUtilities2.stringWidth(progressBar, fontSizer, progressString); if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) { return new Point( x + Math.round(width / 2 - stringWidth / 2), y + ((height + fontSizer.getAscent() - fontSizer.getLeading() - fontSizer.getDescent()) / 2)); } else { // VERTICAL return new Point( x + ((width - fontSizer.getAscent() + fontSizer.getLeading() + fontSizer.getDescent()) / 2), y + Math.round(height / 2 - stringWidth / 2)); } }
/** * Determines the preferred span for this view along an axis. This is implemented to provide the * superclass behavior after first making sure that the current font metrics are cached (for the * nested lines which use the metrics to determine the height of the potentially wrapped lines). * * @param axis may be either View.X_AXIS or View.Y_AXIS * @return the span the view would like to be rendered into. Typically the view is told to render * into the span that is returned, although there is no guarantee. The parent may choose to * resize or break the view. * @see View#getPreferredSpan */ public float getPreferredSpan(int axis) { updateMetrics(); float span = 0; if (axis == View.X_AXIS) { // Add EOL marker span = super.getPreferredSpan(axis); span += metrics.charWidth('\u00b6'); // metrics set in updateMetrics } else { span = super.getPreferredSpan(axis); host = (RSyntaxTextArea) getContainer(); if (host.isCodeFoldingEnabled()) { // TODO: Cache y-offsets again to speed this up // System.out.println("y-axis baby"); int lineCount = host.getLineCount(); FoldManager fm = host.getFoldManager(); for (int i = 0; i < lineCount; i++) { if (fm.isLineHidden(i)) { span -= getSpan(View.Y_AXIS, i); } } } } return span; }
/** * Converts an x co-ordinate to an offset within a line. * * @param line The line * @param x The x co-ordinate */ public int xToOffset(int line, int x) { TokenMarker tokenMarker = getTokenMarker(); /* Use painter's cached info for speed */ FontMetrics fm = painter.getFontMetrics(); getLineText(line, lineSegment); char[] segmentArray = lineSegment.array; int segmentOffset = lineSegment.offset; int segmentCount = lineSegment.count; int width = horizontalOffset; if (tokenMarker == null) { for (int i = 0; i < segmentCount; i++) { char c = segmentArray[i + segmentOffset]; int charWidth; if (c == '\t') charWidth = (int) painter.nextTabStop(width, i) - width; else charWidth = fm.charWidth(c); if (painter.isBlockCaretEnabled()) { if (x - charWidth <= width) return i; } else { if (x - charWidth / 2 <= width) return i; } width += charWidth; } return segmentCount; } else { Token tokens; if (painter.currentLineIndex == line && painter.currentLineTokens != null) tokens = painter.currentLineTokens; else { painter.currentLineIndex = line; tokens = painter.currentLineTokens = tokenMarker.markTokens(lineSegment, line); } int offset = 0; Toolkit toolkit = painter.getToolkit(); Font defaultFont = painter.getFont(); SyntaxStyle[] styles = painter.getStyles(); for (; ; ) { byte id = tokens.id; if (id == Token.END) return offset; if (id == Token.NULL) fm = painter.getFontMetrics(); else fm = styles[id].getFontMetrics(defaultFont); int length = tokens.length; for (int i = 0; i < length; i++) { char c = segmentArray[segmentOffset + offset + i]; int charWidth; if (c == '\t') charWidth = (int) painter.nextTabStop(width, offset + i) - width; else charWidth = fm.charWidth(c); if (painter.isBlockCaretEnabled()) { if (x - charWidth <= width) return offset + i; } else { if (x - charWidth / 2 <= width) return offset + i; } width += charWidth; } offset += length; tokens = tokens.next; } } }
/** * Converts a y co-ordinate to a line index. * * @param y The y co-ordinate */ public int yToLine(int y) { FontMetrics fm = painter.getFontMetrics(); int height = fm.getHeight(); return Math.max(0, Math.min(getLineCount() - 1, y / height + firstLine)); }
/** * Converts a line index to a y co-ordinate. * * @param line The line */ public int lineToY(int line) { FontMetrics fm = painter.getFontMetrics(); return (line - firstLine) * fm.getHeight() - (fm.getLeading() + fm.getMaxDescent()); }
final void updateMetrics() { Component host = getContainer(); Font f = host.getFont(); metrics = host.getFontMetrics(f); // Metrics for the default font. tabSize = getTabSize() * metrics.charWidth('m'); }
private int getTextWidth(String text) { return fmRef.stringWidth(text); }
private int getFontHeight() { return fmRef.getHeight(); }