/** * Get the closest position within the document of the component that has given line and column. * * @param line the first being 1 * @param column the first being 1 * @return the closest position for the text component at given line and column */ public static int getDocumentPosition(JTextComponent editor, int line, int column) { int lineHeight = editor.getFontMetrics(editor.getFont()).getHeight(); int charWidth = editor.getFontMetrics(editor.getFont()).charWidth('m'); int y = line * lineHeight; int x = column * charWidth; Point pt = new Point(x, y); int pos = editor.viewToModel(pt); return pos; }
/** {@inheritDoc} */ public void paint(Graphics g) { if (isVisible() && overwriteMode) { Rectangle r = null; int pos = editor.getCaretPosition(); try { r = editor.modelToView(pos); } catch (BadLocationException e) { } if (r != null && (r.width != 0 || r.height != 0)) { if ((x != r.x) || (y != r.y)) { repaint(); x = r.x; y = r.y; height = r.height; width = editor.getFontMetrics(editor.getFont()).charWidth('W') + 1; } else { g.setColor(editor.getCaretColor()); g.setXORMode(editor.getBackground()); g.fillRect(x, y, width, height); } } } else { super.paint(g); } }
/* (non-Javadoc) * @see org.xamjwg.html.renderer.BaseInputControl#getPreferredWidthImpl(int, int) */ protected int getPreferredWidthImpl(int availWidth, int availHeight) { int size = this.size; if (size == -1) { return 100; } else { JTextComponent widget = this.widget; FontMetrics fm = widget.getFontMetrics(widget.getFont()); Insets insets = widget.getInsets(); return insets.left + insets.right + fm.charWidth('0') * size; } }
/** * Create a line number component for a text component. * * @param argComponent the related text component * @param argMinimumDisplayDigits the number of digits used to calculate the minimum width of the * component. */ public TextLineNumber(JTextComponent argComponent, int argMinimumDisplayDigits) { component = argComponent; setFont(argComponent.getFont()); setBorderGap(5); setCurrentLineForeground(Color.RED); setDigitAlignment(RIGHT); setMinimumDisplayDigits(argMinimumDisplayDigits); argComponent.getDocument().addDocumentListener(this); argComponent.addCaretListener(this); argComponent.addPropertyChangeListener("font", this); }
@Override protected void paintSafely(Graphics g) { super.paintSafely(g); JTextComponent comp = getComponent(); if (hint != null && comp.getText().length() == 0 && (!(hideOnFocus && comp.hasFocus()))) { if (color != null) { g.setColor(color); } else { g.setColor(comp.getForeground().brighter().brighter().brighter()); } int padding = (comp.getHeight() - comp.getFont().getSize()) / 2; g.drawString(hint, 3, comp.getHeight() - padding - 1); } }
/** Returns the baseline for single line text components, like <code>JTextField</code>. */ private static int getSingleLineTextBaseline(JTextComponent textComponent, int h) { View rootView = textComponent.getUI().getRootView(textComponent); if (rootView.getViewCount() > 0) { Insets insets = textComponent.getInsets(); int height = h - insets.top - insets.bottom; int y = insets.top; View fieldView = rootView.getView(0); int vspan = (int) fieldView.getPreferredSpan(View.Y_AXIS); if (height != vspan) { int slop = height - vspan; y += slop / 2; } FontMetrics fm = textComponent.getFontMetrics(textComponent.getFont()); y += fm.getAscent(); return y; } return -1; }
public ClassTextfieldPrompt(String text, JTextComponent component, Show show) { this.component = component; setShow(show); document = component.getDocument(); setText(text); setFont(component.getFont()); setForeground(component.getForeground()); // setBorder(new EmptyBorder(component.getInsets())); setHorizontalAlignment(JLabel.LEADING); component.addFocusListener(this); document.addDocumentListener(this); component.setLayout(new BorderLayout()); component.add(this); checkForPrompt(); }
public BaseInputTextControl(final RenderableContext renderableContext, RenderState renderState) { super(renderableContext); this.renderState = renderState; this.setLayout(WrapperLayout.getInstance()); String value = renderableContext.getAttribute("value"); JTextComponent widget = this.createTextField(); Font font = widget.getFont(); widget.setFont(font.deriveFont(DEFAULT_FONT_SIZE)); widget.setDocument(new LimitedDocument()); widget.setText(value); String maxLengthText = renderableContext.getAttribute("maxlength"); if (maxLengthText != null) { try { this.maxLength = Integer.parseInt(maxLengthText); } catch (NumberFormatException nfe) { // ignore } } this.widget = widget; this.add(widget); }
/** * 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; } } }
/** * Prints a <code>Document</code> using the specified font, word wrapping on the characters ' ', * '\t', '\n', ',', '.', and ';'. This method is expected to be called from Printable * 'print(Graphics g)' functions. * * @param g The graphics context to write to. * @param textComponent The <code>javax.swing.text.JTextComponent</code> whose text you're * printing. * @param font The font to use for printing. If <code>null</code>, then <code>textComponent</code> * 's font is used. * @param pageIndex The page number to print. * @param pageFormat The format to print the page with. * @param tabSize The number of spaces to convert tabs to. */ public static int printDocumentWordWrap( Graphics g, JTextComponent textComponent, Font font, int pageIndex, PageFormat pageFormat, int tabSize) { // Initialize our graphics object. g.setColor(Color.BLACK); g.setFont(font != null ? font : textComponent.getFont()); // Initialize our static variables (these are used by our tab expander below). tabSizeInSpaces = tabSize; fm = g.getFontMetrics(); int fontHeight = fm.getHeight(); final int LINE_LENGTH_IN_PIXELS = (int) pageFormat.getImageableWidth(); final int MAX_LINES_PER_PAGE = (int) pageFormat.getImageableHeight() / fontHeight; final int STARTING_LINE_NUMBER = MAX_LINES_PER_PAGE * pageIndex; // Create our tab expander. RPrintTabExpander tabExpander = new RPrintTabExpander(); // The (x,y) coordinate to print at (in pixels, not characters). // Since y is the baseline of where we'll start printing (not the top-left // corner), we offset it by the font's ascent ( + 1 just for good measure). xOffset = (int) pageFormat.getImageableX(); int y = (int) pageFormat.getImageableY() + fm.getAscent() + 1; // A counter to keep track of the number of lines that WOULD HAVE been // printed if we were printing all lines. int numPrintedLines = 0; // Keep going while there are more lines in the document. Document doc = textComponent.getDocument(); rootElement = doc.getDefaultRootElement(); numDocLines = rootElement.getElementCount(); // The number of lines in our document. currentDocLineNumber = 0; // The line number of the document we're currently on. int startingOffset = 0; // Used when a line is so long it has to be wrapped. while (currentDocLineNumber < numDocLines) { Segment currentLineSeg = new Segment(); // Get the current line (as an Element), and its starting and ending offset in doc. Element currentLine = rootElement.getElement(currentDocLineNumber); int currentLineStart = currentLine.getStartOffset(); int currentLineEnd = currentLine.getEndOffset(); // Put the chars of this line in currentLineSeg, but only starting at our desired offset // (because this line may be the second part of a wrapped line, so we'd start after the part // that has already been printed). try { doc.getText( currentLineStart + startingOffset, currentLineEnd - (currentLineStart + startingOffset), currentLineSeg); } catch (BadLocationException ble) { System.err.println("BadLocationException in print (where there shouldn't be one!): " + ble); return Printable.NO_SUCH_PAGE; } // Remove any spaces and/or tabs from the end of the segment (would cause problems if you left // 'em). currentLineSeg = removeEndingWhitespace(currentLineSeg); // Figger out how long the line is, in pixels. int currentLineLengthInPixels = Utilities.getTabbedTextWidth(currentLineSeg, fm, 0, tabExpander, 0); // System.err.println("'" + currentLineSeg + "' - " + currentLineLengthInPixels + "/" + // LINE_LENGTH_IN_PIXELS); // If it'll fit by itself on a printed line, great. if (currentLineLengthInPixels <= LINE_LENGTH_IN_PIXELS) { currentDocLineNumber += 1; // We (will) have printed one more line from the document. startingOffset = 0; // Start at the first character in the new document line. } // If it won't fit on a printed line by itself (i.e., it needs to be wrapped)... else { // Loop while the current line is too long to fit on a printed line. int currentPos = -1; while (currentLineLengthInPixels > LINE_LENGTH_IN_PIXELS) { // System.err.println("'" + currentLineSeg + "' - " + currentLineLengthInPixels + "/" + // LINE_LENGTH_IN_PIXELS); // Remove any spaces and/or tabs from the end of the segment (would cause problems if you // left 'em). currentLineSeg = removeEndingWhitespace(currentLineSeg); // currentPos will be the last position in the current text of a "line break character." currentPos = -1; String currentLineString = currentLineSeg.toString(); for (int i = 0; i < breakChars.length; i++) { // "+1" below so we include the character on the line. int pos = currentLineString.lastIndexOf(breakChars[i]) + 1; // if (pos>-1 && pos>currentPos) // currentPos = pos; if (pos > 0 && pos > currentPos & pos != currentLineString.length()) currentPos = pos; } // If we didn't find a line break character, we'll simply break the line at // the last character that fits on a printed line. // So here, we set currentPos to be the position of the last character that fits // on the current printed line. if (currentPos == -1) { // Fix currentLineSeg so that it contains exactly enough text to fit in // LINE_LENGTH_IN_PIXELS pixels... currentPos = 0; do { currentPos++; try { doc.getText(currentLineStart + startingOffset, currentPos, currentLineSeg); } catch (BadLocationException ble) { System.err.println(ble); return Printable.NO_SUCH_PAGE; } currentLineLengthInPixels = Utilities.getTabbedTextWidth(currentLineSeg, fm, 0, tabExpander, 0); } while (currentLineLengthInPixels <= LINE_LENGTH_IN_PIXELS); currentPos--; } try { doc.getText((currentLineStart + startingOffset), currentPos, currentLineSeg); } catch (BadLocationException ble) { System.err.println("BadLocationException in print (a):"); System.err.println( "==> currentLineStart: " + currentLineStart + "; startingOffset: " + startingOffset + "; currentPos: " + currentPos); System.err.println( "==> Range: " + (currentLineStart + startingOffset) + " - " + (currentLineStart + startingOffset + currentPos)); ble.printStackTrace(); return Printable.NO_SUCH_PAGE; } currentLineLengthInPixels = Utilities.getTabbedTextWidth(currentLineSeg, fm, 0, tabExpander, 0); } // End of while (currentLineLengthInPixels > LINE_LENGTH_IN_PIXELS). startingOffset += currentPos; // Where to start (offset from line's start), since this line wraps. } // End of else. numPrintedLines++; if (numPrintedLines > STARTING_LINE_NUMBER) { // g.drawString(currentLineSeg.toString(), xOffset,y); Utilities.drawTabbedText(currentLineSeg, xOffset, y, g, tabExpander, 0); y += fontHeight; if (numPrintedLines == STARTING_LINE_NUMBER + MAX_LINES_PER_PAGE) return Printable.PAGE_EXISTS; } } // Now, the whole document has been "printed." Decide if this page had any text on it or not. if (numPrintedLines > STARTING_LINE_NUMBER) return Printable.PAGE_EXISTS; return Printable.NO_SUCH_PAGE; }