public void search() { hilit.removeAllHighlights(); String s = entry.getText(); if (s.length() <= 0) { message("Nothing to search"); return; } String content = textArea.getText(); int index = content.indexOf(s, 0); if (index >= 0) { try { int end = index + s.length(); hilit.addHighlight(index, end, painter); textArea.setCaretPosition(end); entry.setBackground(entryBg); message("'" + s + "' found. Press ESC to end search"); } catch (BadLocationException e) { e.printStackTrace(); } } else { entry.setBackground(ERROR_COLOR); message("'" + s + "' found. Press ESC to start a new search"); } }
protected void insertText(String textString, AttributeSet set) { try { content.getDocument().insertString(content.getDocument().getLength(), textString, set); } catch (BadLocationException e) { e.printStackTrace(); } }
/** * This applies quick fixes which require insertion in the editor panel. * * @param markThisPart */ void insertSentenceStub( IvanErrorInstance myerror, List<String> stubs, String defaultStub, String markThisPart) { String[] unlocatedNames = myerror.Reference; /* Create location sentences. * 1. find the insertion point. The insertion point is somewhere to the right of the last cue. * 2. set the caret to the insertion point * 3. for each Name without location, insert a sentence. (unlocatedNames) * a) build a sentence: Name + Stub. Then insert it. * b) if you run out of stubs, create Name + " is on the … side." and then select the three dots. **/ // focus is important, so the user can readily start typing after clicking txtEditor.requestFocusInWindow(); // get insertion point int insertionpoint = findInsertionPoint(myerror.Codepoints); // set the caret txtEditor.setCaretPosition(insertionpoint); String sentence; if (stubs.size() > 0) { // build a sentence from a stub sentence = "\n" + unlocatedNames[0] + stubs.get(0) + " "; stubs.remove(0); // finalise last sentence with a period, if not present try { String text = txtEditor.getText(insertionpoint - 1, 1); if (!text.equals(".")) { sentence = "." + sentence; } } catch (BadLocationException e1) { e1.printStackTrace(); } // insert the sentence txtEditor.replaceSelection(sentence); } else { sentence = "\n" + unlocatedNames[0] + defaultStub; // finalise last sentence with a period, if not present try { String text = txtEditor.getText(insertionpoint - 1, 1); if (!text.equals(".")) { sentence = "." + sentence; } } catch (BadLocationException e1) { e1.printStackTrace(); } // insert the sentence txtEditor.replaceSelection(sentence); // select the … int dotspoint = txtEditor.getText().indexOf(markThisPart, insertionpoint); if (dotspoint > 0) { txtEditor.setCaretPosition(dotspoint); txtEditor.moveCaretPosition(dotspoint + markThisPart.length()); } } }
@Override public void execute() { // to insert the selected string into the document int pos = editor.getTextPaneEditor().getCaretPosition() - 1; String content = null; try { content = editor.getTextPaneEditor().getText(0, pos + 1); } catch (BadLocationException e) { e.printStackTrace(); } int w; for (w = pos; w >= 0; w--) { if (!Character.isLetter(content.charAt(w))) { break; } } String prefix = content.substring(w + 1).toLowerCase(); try { String toInsert = getName().substring(prefix.length(), getName().length()); String[] args = null; for (Method m : GraphOEditor.class.getMethods()) { if (m.getName().equals(getName())) { if (!(m.getParameterTypes().length == 0)) { args = new String[m.getParameterTypes().length]; } int cpt = 0; for (Class c : m.getParameterTypes()) { args[cpt] = c.getSimpleName(); cpt = cpt + 1; } } } toInsert = toInsert + "("; if (!(args == null)) { for (int i = 0; i < args.length; i++) { if (i == (args.length - 1)) { toInsert = toInsert + args[i]; } else { toInsert = toInsert + args[i] + ","; } } } toInsert = toInsert + ");"; editor.getTextPaneEditor().getDocument().insertString(pos + 1, toInsert, 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(); } }
private Fold findOpenFoldClosestTo(Point p) { Fold fold = null; RSyntaxTextArea rsta = (RSyntaxTextArea) textArea; if (rsta.isCodeFoldingEnabled()) { // Should always be true int offs = rsta.viewToModel(p); // TODO: Optimize me if (offs > -1) { try { int line = rsta.getLineOfOffset(offs); int origLine = line; FoldManager fm = rsta.getFoldManager(); do { fold = fm.getFoldForLine(line); } while (fold == null && line-- >= 0); if (fold != null && !fold.containsOrStartsOnLine(origLine)) { // Found closest fold, but doesn't actually contain line fold = null; } } catch (BadLocationException ble) { ble.printStackTrace(); // Never happens } } } return fold; }
/** * This method causes a transfer to a component from a clipboard or a DND drop operation. The * Transferable represents the data to be imported into the component. * * @param comp The component to receive the transfer. This argument is provided to enable sharing * of TransferHandlers by multiple components. * @param t The data to import * @return <code>true</code> iff the data was inserted into the component. */ public boolean importData(JComponent comp, Transferable t) { JTextComponent c = (JTextComponent) comp; withinSameComponent = c == exportComp; // if we are importing to the same component that we exported from // then don't actually do anything if the drop location is inside // the drag location and set shouldRemove to false so that exportDone // knows not to remove any data if (withinSameComponent && c.getCaretPosition() >= p0 && c.getCaretPosition() <= p1) { shouldRemove = false; return true; } boolean imported = false; DataFlavor importFlavor = getImportFlavor(t.getTransferDataFlavors(), c); if (importFlavor != null) { try { InputContext ic = c.getInputContext(); if (ic != null) ic.endComposition(); Reader r = importFlavor.getReaderForText(t); handleReaderImport(r, c); imported = true; } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); } catch (BadLocationException ble) { ble.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } return imported; }
/** * 将文本插入JTextPane * * @param attrib */ private void insert(FontAttrib attrib) { try { // 插入文本 doc.insertString(doc.getLength(), attrib.getText() + "\n", attrib.getAttrSet()); } catch (BadLocationException e) { e.printStackTrace(); } }
// Displays the users currently online in the usersOnlineWindow JTextArea private void showUsersOnline() throws JSONException { // F**k det här under. Det f*****g sög att skriva. JSONArrays är retarderade. for (int i = 0; i < ((JSONArray) obj.get("listOfUsernames")).length(); i++) { if (!((JSONArray) obj.get("listOfUsernames")).isNull(i)) { if (!doesArrayContain( arrayOfAddedUsernames, ((JSONArray) obj.get("listOfUsernames")).getString(i))) { usersOnlineWindow.append("\n" + ((JSONArray) obj.get("listOfUsernames")).getString(i)); pushValueToArray( arrayOfAddedUsernames, ((JSONArray) obj.get("listOfUsernames")).getString(i)); } } } if (!obj.getString("disconnectedUser").equals("")) { int offset = usersOnlineWindow.getText().indexOf(obj.getString("disconnectedUser")); if (offset != -1) { try { int line = usersOnlineWindow.getLineOfOffset(offset); int start = usersOnlineWindow.getLineStartOffset(line); int end = usersOnlineWindow.getLineEndOffset(line); usersOnlineWindow.replaceRange("", start, end); } catch (BadLocationException e) { e.printStackTrace(); } } obj.put("disconnectedUser", ""); } }
public void displayAllClassesNames(List<String> classNames) { long start = System.currentTimeMillis(); displayDataState = DisplayDataState.CLASSES_LIST; StyleConstants.setFontSize(style, 18); StyleConstants.setForeground(style, ColorScheme.FOREGROUND_CYAN); clearText(); BatchDocument blank = new BatchDocument(); jTextPane.setDocument(blank); for (String className : classNames) { blank.appendBatchStringNoLineFeed(className, style); blank.appendBatchLineFeed(style); } try { blank.processBatchUpdates(0); } catch (BadLocationException e) { e.printStackTrace(); } jTextPane.setDocument(blank); System.out.println("UI update " + (System.currentTimeMillis() - start) + " ms"); }
public void actionPerformed(ActionEvent ae) { updatePanel(); Message message = messagePanel.getMessage(); if (message != null) { JTextPane textPane = messagePanel.getTextPane(); int pos = textPane.getCaretPosition(); Message.Element element = message.findElement(pos); if (logger.isInfoEnabled()) logger.info("Complete element {}.", element); boolean showPopup = false; if (element.getType() == Message.Element.Type.HashTag) { populateHashTags(element); showPopup = true; } else if (element.getType() == Message.Element.Type.Recipient) { populateRecipients(element); showPopup = true; } if (showPopup) { try { Rectangle viewPos = textPane.modelToView(pos); int x = viewPos.x; int y = viewPos.y + viewPos.height; popup.show(textPane, x, y); } catch (BadLocationException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } } } }
private void addStyledText(String text, Style style) { try { doc.insertString(doc.getLength(), text, style); } catch (BadLocationException ble) { ble.printStackTrace(); } }
/** * 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"); } }
protected String getFeatureText() { String txt = ""; try { txt = ((HTMLDocument) getDocument()).getText(0, getDocument().getLength()).trim(); StringBuffer buff = new StringBuffer(); StringTokenizer tok = new StringTokenizer(txt, "/"); int ntok = 0; while (tok.hasMoreTokens()) { String tokTxt = "/" + tok.nextToken().trim(); int ind = tokTxt.indexOf("="); if (ntok != 0 && ind > -1 && qualifier.contains(tokTxt.substring(0, ind + 1))) buff.append("\n" + tokTxt); else buff.append(tokTxt); ntok++; } txt = buff.toString(); } catch (BadLocationException ble) { ble.printStackTrace(); } return txt; }
/** * Called when a user processing input characters and select candidates from input method. * * @param text Text from InputMethodEvent. * @param commited_count Numbers of committed characters in text. */ public void processCompositionText(AttributedCharacterIterator text, int committed_count) { int layoutCaretPosition = initialCaretPosition + committed_count; CompositionTextPainter compositionPainter = textArea.getPainter().getCompositionTextpainter(); compositionPainter.setComposedTextLayout( getTextLayout(text, committed_count), layoutCaretPosition); int textLength = text.getEndIndex() - text.getBeginIndex() - committed_count; StringBuffer unCommitedStringBuf = new StringBuffer(textLength); char c; for (c = text.setIndex(committed_count); c != AttributedCharacterIterator.DONE && textLength > 0; c = text.next(), --textLength) { unCommitedStringBuf.append(c); } String unCommittedString = unCommitedStringBuf.toString(); try { if (canRemovePreviousInput(committed_count)) { textArea.getDocument().remove(layoutCaretPosition, prevComposeString.length()); } textArea.getDocument().insertString(layoutCaretPosition, unCommittedString, null); if (committed_count > 0) { initialCaretPosition = initialCaretPosition + committed_count; } prevComposeString = unCommittedString; prevCommittedCount = committed_count; } catch (BadLocationException e) { e.printStackTrace(); } }
public void actionPerformed(ActionEvent evt) { JEditTextArea textArea = getTextArea(evt); if(!textArea.isEditable()) { textArea.getToolkit().beep(); return; } if(textArea.getSelectionStart() != textArea.getSelectionEnd()) { textArea.setSelectedText(""); } else { int caret = textArea.getCaretPosition(); if(caret == textArea.getDocumentLength()) { textArea.getToolkit().beep(); return; } try { textArea.getDocument().remove(caret,1); } catch(BadLocationException bl) { bl.printStackTrace(); } } }
public void toggleBreakpoint() { if (isEnabled()) { try { int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition(); lastClickPoint = null; if (position >= 0) { String textToCaret = getDocument().getText(0, position); int lineCount = 0; for (int i = 0; i < textToCaret.length(); i++) { if (textToCaret.charAt(i) == '\n') { lineCount++; } } if (breakpoints.isThereBreakpoint(lineCount)) { breakpoints.removeBreakpoint(lineCount); } else { breakpoints.addBreakpoint(new BreakpointInfo(lineCount)); } } } catch (BadLocationException e) { e.printStackTrace(); } Component parent = GuiUtils.getParentOfType(this, XmlEditorScrollPane.class); if (parent != null) { ((XmlEditorScrollPane) parent).onDocChanged(); } repaint(); } }
/** * Similar to <code>setSelectedText()</code>, but overstrikes the appropriate number of characters * if overwrite mode is enabled. * * @param str The string * @see #setSelectedText(String) * @see #isOverwriteEnabled() */ public void overwriteSetSelectedText(String str) { // Don't overstrike if there is a selection if (!overwrite || selectionStart != selectionEnd) { setSelectedText(str); return; } // Don't overstrike if we're on the end of // the line int caret = getCaretPosition(); int caretLineEnd = getLineEndOffset(getCaretLine()); if (caretLineEnd - caret <= str.length()) { setSelectedText(str); return; } document.beginCompoundEdit(); try { document.remove(caret, str.length()); document.insertString(caret, str, null); } catch (BadLocationException bl) { bl.printStackTrace(); } finally { document.endCompoundEdit(); } }
public void mousePressed(MouseEvent evt) { requestFocus(); // Focus events not fired sometimes? setCaretVisible(true); focusedComponent = JEditTextArea.this; if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0 && popup != null) { popup.show(painter, evt.getX(), evt.getY()); return; } int line = yToLine(evt.getY()); int offset = xToOffset(line, evt.getX()); int dot = getLineStartOffset(line) + offset; switch (evt.getClickCount()) { case 1: doSingleClick(evt, line, offset, dot); break; case 2: // It uses the bracket matching stuff, so // it can throw a BLE try { doDoubleClick(evt, line, offset, dot); } catch (BadLocationException bl) { bl.printStackTrace(); } break; case 3: doTripleClick(evt, line, offset, dot); break; } }
public void valueChanged(ListSelectionEvent e) { if (e.getSource() == _table.getSelectionModel()) { _table.getPathForRow(_table.getSelectedRow()); // is there already a highlighted part? if (_currentSelectedPart != null) { // unhighlight previous selected text // restoring its style try { String text = _hexStyledDoc.getText( _currentSelectedPart.getOffset(), _currentSelectedPart.getLength()); _hexStyledDoc.remove( _currentSelectedPart.getOffset(), _currentSelectedPart.getLength()); _hexStyledDoc.insertString( _currentSelectedPart.getOffset(), text, _hexStyledDoc.getStyle( _currentSelectedPart.getPacketNode().getModelPart().getType().getName())); } catch (BadLocationException e1) { e1.printStackTrace(); } } TreePath tp = _table.getPathForRow(_table.getSelectedRow()); if (tp != null && ((DataPartNode) tp.getLastPathComponent()).isLeaf()) { _currentSelectedPart = (DataPartNode) tp.getLastPathComponent(); ViewPane.this.highlightSelectedPart(_currentSelectedPart); } } }
/** * Workaround for JEditorPane not returning its proper preferred size when rendering HTML until * after layout already done. See http://forums.sun.com/thread.jspa?forumID=57&threadID=574810 for * a discussion. */ void fixSize() { Dimension d = textArea.getPreferredSize(); Rectangle r = null; try { // modelToView call is required for this hack, never remove! r = textArea.modelToView(textArea.getDocument().getLength() - 1); // Ensure the text area doesn't start out too tall or wide. d = textArea.getPreferredSize(); d.width += 25; // Just a little extra space final int MAX_WINDOW_W = 600; d.width = Math.min(d.width, MAX_WINDOW_W); d.height = Math.min(d.height, 400); // Both needed for modelToView() calculation below... textArea.setPreferredSize(d); textArea.setSize(d); // if the new textArea width causes our text to wrap, we must // compute a new preferred size to get all our physical lines. r = textArea.modelToView(textArea.getDocument().getLength() - 1); if (r.y + r.height > d.height) { d.height = r.y + r.height + 5; textArea.setPreferredSize(d); } } catch (BadLocationException ble) { // Never happens ble.printStackTrace(); } pack(); // Must re-pack to calculate proper size. }
/** * Selects a range of text in a text component. If the new selection is outside of the previous * viewable rectangle, then the view is centered around the new selection. * * @param textArea The text component whose selection is to be centered. * @param start The start of the range to select. * @param end The end of the range to select. */ private static void selectAndPossiblyCenter(JTextArea textArea, int start, int end) { textArea.setSelectionStart(start); textArea.setSelectionEnd(end); Rectangle r = null; try { r = textArea.modelToView(start); if (r == null) { // Not yet visible; i.e. JUnit tests return; } if (end != start) { r = r.union(textArea.modelToView(end)); } } catch (BadLocationException ble) { // Never happens ble.printStackTrace(); textArea.setSelectionStart(start); textArea.setSelectionEnd(end); return; } Rectangle visible = textArea.getVisibleRect(); // If the new selection is already in the view, don't scroll, // as that is visually jarring. if (visible.contains(r)) { textArea.setSelectionStart(start); textArea.setSelectionEnd(end); return; } visible.x = r.x - (visible.width - r.width) / 2; visible.y = r.y - (visible.height - r.height) / 2; Rectangle bounds = textArea.getBounds(); Insets i = textArea.getInsets(); bounds.x = i.left; bounds.y = i.top; bounds.width -= i.left + i.right; bounds.height -= i.top + i.bottom; if (visible.x < bounds.x) { visible.x = bounds.x; } if (visible.x + visible.width > bounds.x + bounds.width) { visible.x = bounds.x + bounds.width - visible.width; } if (visible.y < bounds.y) { visible.y = bounds.y; } if (visible.y + visible.height > bounds.y + bounds.height) { visible.y = bounds.y + bounds.height - visible.height; } textArea.scrollRectToVisible(visible); }
public static void setColorss(String str, Color col) { try { setColors(str, col); } catch (BadLocationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
/** * Insert some stylish text. * * @param position the position where to insert the text * @param text the text to insert * @param set the formatting attributes */ public void styled(int position, String text, AttributeSet set) { try { document.insertString(position, text, set); } catch (BadLocationException e) { e.printStackTrace(); throw new RuntimeException(e); } }
@Override public void clearLog() { try { this.txtLog.getStyledDocument().remove(0, txtLog.getStyledDocument().getLength()); } catch (BadLocationException e) { e.printStackTrace(); } }
/** * Copies the specified substring of the document into a segment. If the offsets are invalid, the * segment will contain a null string. * * @param start The start offset * @param len The length of the substring * @param segment The segment */ public final void getText(int start, int len, Segment segment) { try { document.getText(start, len, segment); } catch (BadLocationException bl) { bl.printStackTrace(); segment.offset = segment.count = 0; } }
/** * Returns the specified substring of the document. * * @param start The start offset * @param len The length of the substring * @return The substring, or null if the offsets are invalid */ public final String getText(int start, int len) { try { return document.getText(start, len); } catch (BadLocationException bl) { bl.printStackTrace(); return null; } }
/** Returns the entire text of this text area. */ public String getText() { try { return document.getText(0, document.getLength()); } catch (BadLocationException bl) { bl.printStackTrace(); return null; } }
/** * @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; } }
public String getDocumentText() { try { return getDocument().getText(0, getDocument().getLength()); } catch (BadLocationException e) { e.printStackTrace(); return null; } }