/** * Parse the passed text string for style names and add the styled text to the text pane's * document. * * @param text Text to parse * @param pane Pane to modify. The pane also provides the style names */ public static final void parse(String text, JTextPane pane) { try { Matcher match = TEXT_PATTERN.matcher(text); Document doc = pane.getDocument(); int textStart = 0; // Start of current text area Style style = null; // Style for next set of text while (match.find()) { // Save the current text first String styledText = text.substring(textStart, match.start()); textStart = match.end() + 1; if (style != null && styledText != null) { doc.insertString(doc.getLength(), styledText, style); } // endif // Get the next style style = pane.getStyle(match.group(1)); if (style == null) throw new IllegalArgumentException("Unknown style: '" + match.group(1)); } // endwhile // Add the last of the text doc.insertString(doc.getLength(), text.substring(textStart), null); } catch (BadLocationException e) { e.printStackTrace(); throw new IllegalStateException( "This should not happen since I always use the document to " + "determine the location to write. It might be due to synchronization problems though"); } }
/** * Attempts to find the next subsequence of the input sequence that matches the pattern. * * <p>This method starts at the beginning of the input sequence or, if a previous invocation of * the method was successful and the matcher has not since been reset, at the first character not * matched by the previous match. * * @return the index of the first occurrence of the search string, starting at the specified * offset, or -1 if no occurrence was found. */ public int findNext() { // Don't match empty strings and don't match if we are at the end of the document. if (findString.length() == 0 || document.getLength() - findString.length() < startIndex) { return -1; } try { int nextMatch = 0; // index of next matching character // Iterate through all segments of the document starting from offset Segment text = new Segment(); text.setPartialReturn(true); int offset = startIndex; int nleft = document.getLength() - startIndex; while (nleft > 0) { document.getText(offset, nleft, text); // Iterate through the characters in the current segment char next = text.first(); for (text.first(); next != Segment.DONE; next = text.next()) { // Check if the current character matches with the next // search character. char current = text.current(); if (current == matchUpperCase[nextMatch] || current == matchLowerCase[nextMatch]) { nextMatch++; // Did we match all search characters? if (nextMatch == matchLowerCase.length) { int foundIndex = text.getIndex() - text.getBeginIndex() + offset - matchLowerCase.length + 1; if (matchType == MatchType.CONTAINS) { return foundIndex; // break; <- never reached } else if (matchType == MatchType.STARTS_WITH) { if (!isWordChar(foundIndex - 1)) { return foundIndex; } } else if (matchType == MatchType.FULL_WORD) { if (!isWordChar(foundIndex - 1) && !isWordChar(foundIndex + matchLowerCase.length)) { return foundIndex; } } nextMatch = 0; } } else { nextMatch = 0; } } // Move forward to the next segment nleft -= text.count; offset += text.count; } return -1; } catch (BadLocationException e) { throw new IndexOutOfBoundsException(); } }
private void populateRemark() { txtTextField.setText(""); txtRemark.setText(""); SimpleAttributeSet BLUE = new SimpleAttributeSet(); SimpleAttributeSet BLACK = new SimpleAttributeSet(); StyleConstants.setForeground(BLUE, Color.BLUE); StyleConstants.setForeground(BLACK, Color.BLACK); Document rmkDoc = txtRemark.getDocument(); for (int i = remarkslist.size() - 1; i >= 0; i--) { RemarkSummary prmk = remarkslist.get(i); try { if (prmk.getCreatedBy() == null) { rmkDoc.insertString(rmkDoc.getLength(), "" + "" + "" + "", BLUE); } else { rmkDoc.insertString( rmkDoc.getLength(), prmk.getDateTime() + " : " + prmk.getCreatedBy() + " : ", BLUE); } rmkDoc.insertString(rmkDoc.getLength(), prmk.getText() + '\n', BLACK); } catch (BadLocationException e) { System.out.println("Exception in pnr remark: " + e); } } }
// TODO not used public void appendString(String str) { Document doc = getDocument(); try { int start = doc.getLength(); doc.insertString(doc.getLength(), str, null); int end = doc.getLength(); // end = parseLine(start, end, patHistoryBtnStr); } catch (Exception e) { Debug.error(me + "appendString: Problem while trying to append\n%s", e.getMessage()); } }
private void updateBoard(DocumentEvent e) throws BadLocationException { Document doc = e.getDocument(); int index = (int) doc.getProperty("index"); String valueString = doc.getText(0, doc.getLength()); if (doc.getLength() == 0) valueString = "0"; int value = Integer.parseInt(valueString); gameBoard.changeCellAt(index, value); // gameBoard.out(); if (gameBoard.checkGameOver()) { JOptionPane.showMessageDialog(frame, "NUMBRIX COMPLETED!!!"); } }
@Override @SuppressWarnings("SleepWhileHoldingLock") public void run() { try { // initialize the statusbar status.removeAll(); JProgressBar progress = new JProgressBar(); progress.setMinimum(0); progress.setMaximum(doc.getLength()); status.add(progress); status.revalidate(); // start writing Writer out = new FileWriter(f); Segment text = new Segment(); text.setPartialReturn(true); int charsLeft = doc.getLength(); int offset = 0; while (charsLeft > 0) { doc.getText(offset, Math.min(4096, charsLeft), text); out.write(text.array, text.offset, text.count); charsLeft -= text.count; offset += text.count; progress.setValue(offset); try { Thread.sleep(10); } catch (InterruptedException e) { Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, e); } } out.flush(); out.close(); } catch (IOException e) { final String msg = e.getMessage(); SwingUtilities.invokeLater( new Runnable() { public void run() { JOptionPane.showMessageDialog( getFrame(), "Could not save file: " + msg, "Error saving file", JOptionPane.ERROR_MESSAGE); } }); } catch (BadLocationException e) { System.err.println(e.getMessage()); } // we are done... get rid of progressbar status.removeAll(); status.revalidate(); }
private void processChosenFromCompletion(boolean nameOnly) { final LookupFile file = getSelectedFileFromCompletionPopup(); if (file == null) return; if (nameOnly) { try { final Document doc = myPathTextField.getDocument(); int caretPos = myPathTextField.getCaretPosition(); if (myFinder.getSeparator().equals(doc.getText(caretPos, 1))) { for (; caretPos < doc.getLength(); caretPos++) { final String eachChar = doc.getText(caretPos, 1); if (!myFinder.getSeparator().equals(eachChar)) break; } } int start = caretPos > 0 ? caretPos - 1 : caretPos; while (start >= 0) { final String each = doc.getText(start, 1); if (myFinder.getSeparator().equals(each)) { start++; break; } start--; } int end = start < caretPos ? caretPos : start; while (end <= doc.getLength()) { final String each = doc.getText(end, 1); if (myFinder.getSeparator().equals(each)) { break; } end++; } if (end > doc.getLength()) { end = doc.getLength(); } if (start > end || start < 0 || end > doc.getLength()) { setTextToFile(file); } else { replacePathComponent(file, caretPos, start, end); } } catch (BadLocationException e) { LOG.error(e); } } else { setTextToFile(file); } }
private static void insertQuestion(final JTextPane textPane, String str) { Document doc = textPane.getDocument(); try { doc.insertString(doc.getLength(), str, null); final int pos = doc.getLength(); System.out.println(pos); final JTextField field = new JTextField(4) { @Override public Dimension getMaximumSize() { return getPreferredSize(); } }; field.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK)); field.addFocusListener( new FocusListener() { @Override public void focusGained(FocusEvent e) { try { Rectangle rect = textPane.modelToView(pos); rect.grow(0, 4); rect.setSize(field.getSize()); // System.out.println(rect); // System.out.println(field.getLocation()); textPane.scrollRectToVisible(rect); } catch (BadLocationException ex) { ex.printStackTrace(); } } @Override public void focusLost(FocusEvent e) { /* not needed */ } }); Dimension d = field.getPreferredSize(); int baseline = field.getBaseline(d.width, d.height); field.setAlignmentY(baseline / (float) d.height); SimpleAttributeSet a = new SimpleAttributeSet(); StyleConstants.setLineSpacing(a, 1.5f); textPane.setParagraphAttributes(a, true); textPane.insertComponent(field); doc.insertString(doc.getLength(), "\n", null); } catch (BadLocationException e) { e.printStackTrace(); } }
public void execute() { if (!isEditable() || !isEnabled()) { return; } try { int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition(); lastClickPoint = null; Document document = getDocument(); String selectedText = getSelectedText(); if (selectedText != null && !CommonUtil.isEmpty(selectedText)) { final int selectionEnd = getSelectionEnd(); document.insertString(selectionEnd, selectedText, null); select(selectionEnd, selectionEnd + selectedText.length()); } else { final int docLen = document.getLength(); int fromIndex = Math.max(0, getText(0, position).lastIndexOf('\n')); int toIndex = getText(fromIndex + 1, docLen - fromIndex).indexOf('\n'); toIndex = toIndex < 0 ? docLen : fromIndex + toIndex; String textToDuplicate = getText(fromIndex, toIndex - fromIndex + 1); if (!textToDuplicate.startsWith("\n")) { textToDuplicate = "\n" + textToDuplicate; } if (textToDuplicate.endsWith("\n")) { textToDuplicate = textToDuplicate.substring(0, textToDuplicate.length() - 1); } document.insertString(Math.min(docLen, toIndex + 1), textToDuplicate, null); setCaretPosition(position + textToDuplicate.length()); } } catch (BadLocationException e1) { e1.printStackTrace(); } }
/** Replaces the current word token */ public void replaceWord(String newWord) { if (currentWordPos != -1) { try { /* ORIGINAL document.remove(currentWordPos, currentWordEnd - currentWordPos); document.insertString(currentWordPos, newWord, null); */ // Howard's Version for Ekit Element element = ((javax.swing.text.html.HTMLDocument) document).getCharacterElement(currentWordPos); AttributeSet attribs = element.getAttributes(); document.remove(currentWordPos, currentWordEnd - currentWordPos); document.insertString(currentWordPos, newWord, attribs); // End Howard's Version // Need to reset the segment document.getText(0, document.getLength(), text); } catch (BadLocationException ex) { throw new RuntimeException(ex.getMessage()); } // Position after the newly replaced word(s) // Position after the newly replaced word(s) first = true; currentWordPos = getNextWordStart(text, currentWordPos + newWord.length()); if (currentWordPos != -1) { currentWordEnd = getNextWordEnd(text, currentWordPos); nextWordPos = getNextWordStart(text, currentWordEnd); sentanceIterator.setText(text); sentanceIterator.following(currentWordPos); } else moreTokens = false; } }
public void print(final String line) { if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater( new Runnable() { public void run() { ConsoleTab.this.print(line); } }); return; } Document document = this.console.getDocument(); JScrollBar scrollBar = getVerticalScrollBar(); boolean shouldScroll = false; if (getViewport().getView() == this.console) { shouldScroll = scrollBar.getValue() + scrollBar.getSize().getHeight() + MONOSPACED.getSize() * 4 > scrollBar.getMaximum(); } try { document.insertString(document.getLength(), line, null); } catch (BadLocationException localBadLocationException) { } if (shouldScroll) scrollBar.setValue(2147483647); }
void appendOutput(final String line) { if (!EventQueue.isDispatchThread()) { EventQueue.invokeLater( new Runnable() { public void run() { appendOutput(line); } }); return; } if (!isShowing()) { // ignore request, dialog is closed return; } // Can now accept user input outputArea.setEditable(true); Document doc = outputArea.getDocument(); if (doc != null) { try { doc.insertString(doc.getLength(), line + "\n", null); // NOI18N } catch (BadLocationException e) { } } }
public void keyPressed(KeyEvent event) { try { switch (event.getKeyCode()) { case KeyEvent.VK_ENTER: try { processInput.write(getLastLine(textComponent.getDocument()).getBytes()); processInput.flush(); } catch (IOException ioe) { Exceptions.printStackTrace(ioe); } break; case KeyEvent.VK_BACK_SPACE: Document doc = textComponent.getDocument(); if (!"\n".equals(getLastChar(doc))) { // NOI18N startOffset = doc.getLength() - 1; doc.remove(startOffset, 1); } break; } } catch (BadLocationException ex) { } // be sure caret position is adjusted in the case user move it from the end of doc textComponent.setCaretPosition(textComponent.getDocument().getLength()); startOffset = textComponent.getDocument().getLength(); }
/** * Log a message given the {@link AttributeSet}. * * @param line line * @param attributes attribute set, or null for none */ public void log(String line, AttributeSet attributes) { if (colorEnabled) { if (line.startsWith("(!!)")) { attributes = highlightedAttributes; } } try { int offset = document.getLength(); document.insertString( offset, line, (attributes != null && colorEnabled) ? attributes : defaultAttributes); textComponent.setCaretPosition(document.getLength()); } catch (BadLocationException ble) { } catch (NullPointerException npe) { } }
/** * Накат истории вперед * * @param target Запись истории * @param textPane Текст для которого применяется историческое изменение */ public static void applyForward(UndoTextAction target, JTextComponent textPane) { if (target == null) throw new IllegalArgumentException("target==null"); if (textPane == null) throw new IllegalArgumentException("textPane==null"); try { javax.swing.text.Document doc = textPane.getDocument(); int offset = target.getOffset(); String changes = target.getChangedText(); if (UndoTextAction.Action.Added.equals(target.getAction())) { doc.insertString(offset, changes, null); int L = doc.getLength(); int P = offset + changes.length(); if (P > L) P = L; textPane.setCaretPosition(P); } else if (UndoTextAction.Action.Deleted.equals(target.getAction())) { doc.remove(offset, changes.length()); textPane.setCaretPosition(offset); } } catch (BadLocationException ex) { Logger.getLogger(UndoTextAction.class.getName()).log(Level.SEVERE, null, ex); } }
/* * Check whether the prompt should be visible or not. The visibility will * change on updates to the Document and on focus changes. */ private void checkForPrompt() { // Text has been entered, remove the prompt if (document.getLength() > 0) { setVisible(false); return; } // Prompt has already been shown once, remove it if (showPromptOnce && focusLost > 0) { setVisible(false); return; } // Check the Show property and component focus to determine if the // prompt should be displayed. if (component.hasFocus()) { if (show == Show.ALWAYS || show == Show.FOCUS_GAINED) { setVisible(true); } else { setVisible(false); } } else { if (show == Show.ALWAYS || show == Show.FOCUS_LOST) { setVisible(true); } else { setVisible(false); } } }
public void actionPerformed(ActionEvent evt) { Document document = outputArea.getDocument(); try { document.remove(0, document.getLength()); } catch (BadLocationException ble) { } }
public void highlight(JTextComponent textComp, String pattern) { if (pattern.isEmpty()) { textComp.getHighlighter().removeAllHighlights(); return; } try { Highlighter hilite = textComp.getHighlighter(); hilite.removeAllHighlights(); javax.swing.text.Document doc = textComp.getDocument(); String text = doc.getText(0, doc.getLength()); int pos = 0; if (!check.isSelected()) { pattern = pattern.toLowerCase(); text = text.toLowerCase(); } // Search for pattern while ((pos = text.indexOf(pattern, pos)) >= 0) { // Create highlighter using private painter and apply around // pattern hilite.addHighlight(pos, pos + pattern.length(), painter); pos += pattern.length(); } } catch (Exception e) { new the.bytecode.club.bytecodeviewer.api.ExceptionUI(e); } }
/** * Returns offset of the given word in src the component * * @param src source component * @param word desired word * @return position offset */ public static int searchInTxComp(JTextComponent src, String word) { int firstOffset = -1; if (word == null || word.isEmpty()) { return -1; } // Look for the word we are given - insensitive searchInTxComp String content = null; try { Document d = src.getDocument(); content = d.getText(0, d.getLength()).toLowerCase(); } catch (BadLocationException e) { // Cannot happen return -1; } word = word.toLowerCase(); int lastIndex = 0; int wordSize = word.length(); while ((lastIndex = content.indexOf(word, lastIndex)) != -1) { int endIndex = lastIndex + wordSize; if (firstOffset == -1) { firstOffset = lastIndex; } lastIndex = endIndex; } return firstOffset; }
/** * Updates the AttributedCharacterIterator by invoking <code>formatToCharacterIterator</code> on * the <code>Format</code>. If this is successful, <code>updateMask(AttributedCharacterIterator) * </code> is then invoked to update the internal bitmask. */ void updateMask() { if (getFormat() != null) { Document doc = getFormattedTextField().getDocument(); validMask = false; if (doc != null) { try { string = doc.getText(0, doc.getLength()); } catch (BadLocationException ble) { string = null; } if (string != null) { try { Object value = stringToValue(string); AttributedCharacterIterator iterator = getFormat().formatToCharacterIterator(value); updateMask(iterator); } catch (ParseException pe) { } catch (IllegalArgumentException iae) { } catch (NullPointerException npe) { } } } } }
/** * Returns the end of the word at the given offset. * * @param textArea The text area. * @param offs The offset into the text area's content. * @return The end offset of the word. * @throws BadLocationException If <code>offs</code> is invalid. * @see #getWordStart(RSyntaxTextArea, int) */ public static int getWordEnd(RSyntaxTextArea textArea, int offs) throws BadLocationException { Document doc = textArea.getDocument(); int endOffs = textArea.getLineEndOffsetOfCurrentLine(); int lineEnd = Math.min(endOffs, doc.getLength()); if (offs == lineEnd) { // End of the line. return offs; } String s = doc.getText(offs, lineEnd - offs - 1); if (s != null && s.length() > 0) { // Should always be true int i = 0; int count = s.length(); char ch = s.charAt(i); if (Character.isWhitespace(ch)) { while (i < count && Character.isWhitespace(s.charAt(i++))) ; } else if (Character.isLetterOrDigit(ch)) { while (i < count && Character.isLetterOrDigit(s.charAt(i++))) ; } else { i = 2; } offs += i - 1; } return offs; }
/** * Returns the start of the word at the given offset. * * @param textArea The text area. * @param offs The offset into the text area's content. * @return The start offset of the word. * @throws BadLocationException If <code>offs</code> is invalid. * @see #getWordEnd(RSyntaxTextArea, int) */ public static int getWordStart(RSyntaxTextArea textArea, int offs) throws BadLocationException { Document doc = textArea.getDocument(); Element line = getLineElem(doc, offs); if (line == null) { throw new BadLocationException("No word at " + offs, offs); } int lineStart = line.getStartOffset(); if (offs == lineStart) { // Start of the line. return offs; } int endOffs = Math.min(offs + 1, doc.getLength()); String s = doc.getText(lineStart, endOffs - lineStart); if (s != null && s.length() > 0) { int i = s.length() - 1; char ch = s.charAt(i); if (Character.isWhitespace(ch)) { while (i > 0 && Character.isWhitespace(s.charAt(i - 1))) { i--; } offs = lineStart + i; } else if (Character.isLetterOrDigit(ch)) { while (i > 0 && Character.isLetterOrDigit(s.charAt(i - 1))) { i--; } offs = lineStart + i; } } return offs; }
/** @param singleFormatter */ protected void fillWithObjFormatter(final DataObjDataFieldFormatIFace singleFormatter) { ignoreFmtChange = true; try { formatEditor.setText(""); if (singleFormatter == null) { return; } Document doc = formatEditor.getDocument(); DataObjDataField[] fields = singleFormatter.getFields(); if (fields == null) { return; } for (DataObjDataField field : fields) { try { doc.insertString(doc.getLength(), field.getSep(), null); // System.err.println("["+field.getName()+"]["+field.getSep()+"]["+field.getFormat()+"]["+field.toString()+"]"); insertFieldIntoTextEditor(new DataObjDataFieldWrapper(field)); } catch (BadLocationException ble) { } } } finally { ignoreFmtChange = false; } }
private void logResult(JEditorPane e, String s) { Document doc = e.getDocument(); try { doc.insertString(doc.getLength(), s, null); } catch (BadLocationException e1) { /* empty */ } }
/** * @param document * @return True if given document is a dtbook. */ private static boolean isDtBook(final Document document) { try { return document.getText(0, document.getLength()).contains("<dtbook"); } catch (final BadLocationException e) { e.printStackTrace(); return false; } }
protected void insert(String s, boolean ortholog) { s = getDatabaseHTML(s, "SWALL:"); s = getDatabaseHTML(s, "UniProt:"); s = getDatabaseHTML(s, "EMBL:"); s = getGeneDBHTML(s); // int ind = s.indexOf("/gene"); Document doc = getDocument(); int offset = doc.getLength(); if (ortholog) offset = startRange; insert(s, offset); setCaretPosition(doc.getLength()); // reportHTML(); }
protected void append(JTextPane field, final String change) { Document document = field.getDocument(); try { document.insertString(document.getLength(), change, null); } catch (BadLocationException e) { throw new NotImplementedYet(e); // Fix Handle this exception. } }
@Override public java.lang.String getValue() { try { return document.getText(0, document.getLength()); } catch (final BadLocationException e) { throw new RuntimeException(e); } }
private void addText(String str, String styleName, JTextPane pane) { Document doc = pane.getDocument(); int len = doc.getLength(); try { doc.insertString(len, str, pane.getStyle(styleName)); } catch (javax.swing.text.BadLocationException e) { } }
public void clearText() { try { Document doc = textPane.getDocument(); doc.remove(0, doc.getLength()); } catch (Exception ex) { log.warn("failed to clear text", ex); } }