@Override protected Transferable createTransferable(JComponent c) { JTextPane aTextPane = (JTextPane) c; HTMLEditorKit kit = ((HTMLEditorKit) aTextPane.getEditorKit()); StyledDocument sdoc = aTextPane.getStyledDocument(); int sel_start = aTextPane.getSelectionStart(); int sel_end = aTextPane.getSelectionEnd(); int i = sel_start; StringBuilder output = new StringBuilder(); while (i < sel_end) { Element e = sdoc.getCharacterElement(i); Object nameAttr = e.getAttributes().getAttribute(StyleConstants.NameAttribute); int start = e.getStartOffset(), end = e.getEndOffset(); if (nameAttr == HTML.Tag.BR) { output.append("\n"); } else if (nameAttr == HTML.Tag.CONTENT) { if (start < sel_start) { start = sel_start; } if (end > sel_end) { end = sel_end; } try { String str = sdoc.getText(start, end - start); output.append(str); } catch (BadLocationException ble) { Debug.error(me + "Copy-paste problem!\n%s", ble.getMessage()); } } i = end; } return new StringSelection(output.toString()); }
protected void insertText(String textString, AttributeSet set) { try { content.getDocument().insertString(content.getDocument().getLength(), textString, set); } catch (BadLocationException e) { e.printStackTrace(); } }
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"); } }
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(); } }
/** * 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; }
/** Clear the log panel. */ public void clearLogPanel() { try { logPane.getDocument().remove(1, logPane.getDocument().getLength() - 1); } catch (BadLocationException e) { LoggerFactory.getLogger(ProcessUIPanel.class).error(e.getMessage()); } }
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); } } }
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 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"); }
/** 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; } }
private void addStyledText(String text, Style style) { try { doc.insertString(doc.getLength(), text, style); } catch (BadLocationException ble) { ble.printStackTrace(); } }
/** Initialize document with information from the settings. */ private void initDocument(final GuardedDocument<Section> doc) { try { if (this.m_settings != null) { String script = this.m_settings.getScript(); if (script != null && !script.isEmpty()) { doc.setBreakGuarded(true); doc.replace(0, doc.getLength(), this.m_settings.getScript(), null); doc.setBreakGuarded(false); Map<Section, int[]> scriptParts = this.m_settings.getScriptParts(); for (Map.Entry<Section, int[]> scriptPart : scriptParts.entrySet()) { doc.getGuardedSection(scriptPart.getKey()) .setStart(doc.createPosition(scriptPart.getValue()[0])); doc.getGuardedSection(scriptPart.getKey()) .setEnd(doc.createPosition(scriptPart.getValue()[1])); } } } else this.initGuardedSection(doc); // doc.replaceBetween(Section.Imports, Section.JobStart, this.m_settings.getScriptImports()); // doc.replaceBetween(GUARDED_FIELDS, Section.TaskStart, this.m_settings.getScriptFields()); // doc.replaceBetween(Section.TaskStart, GUARDED_TASK_END, this.m_settings.getScriptBody()); // } } catch (BadLocationException e) { throw new IllegalStateException(e.getMessage(), e); } }
/** * 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; }
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 static int getNSVisualPosition(EditorPane txt, int pos, int direction) { Element root = txt.getDocument().getDefaultRootElement(); int numLines = root.getElementIndex(txt.getDocument().getLength() - 1) + 1; int line = root.getElementIndex(pos) + 1; int tarLine = direction == SwingConstants.NORTH ? line - 1 : line + 1; try { if (tarLine <= 0) { return 0; } if (tarLine > numLines) { return txt.getDocument().getLength(); } Rectangle curRect = txt.modelToView(pos); Rectangle tarEndRect; if (tarLine < numLines) { tarEndRect = txt.modelToView(txt.getLineStartOffset(tarLine) - 1); } else { tarEndRect = txt.modelToView(txt.getDocument().getLength() - 1); } Debug.log(9, "curRect: " + curRect + ", tarEnd: " + tarEndRect); if (curRect.x > tarEndRect.x) { pos = txt.viewToModel(new Point(tarEndRect.x, tarEndRect.y)); } else { pos = txt.viewToModel(new Point(curRect.x, tarEndRect.y)); } } catch (BadLocationException e) { Debug.error(me + "Problem getting next visual position\n%s", e.getMessage()); } return pos; }
// ---------------------------------------------------- // return last location found public int searchBackward(String lastFindStr) { try { // backward if (isFindAgain) { // otherwise you find same string int foo = lastFindIndex; // begining of word if (foo >= 0) { editor1.setCaretPosition(foo); } // System.out.println("Debug:TextViewer:searchBackward: lastFindIndex: "+foo); } int carPos = editor1.getCaretPosition(); // search backward // todo: should we use the getText(pos,len,segment); String chunk1 = editor1.getDocument().getText(0, carPos); int lastFindIndexTemp = chunk1.lastIndexOf(lastFindStr); if (lastFindIndexTemp == -1) { boolean okPressed = okCancelPopup.display("TextViewer:string not found. Try forward?"); // handle forward if (okPressed) { forwardFindDirection = true; lastFindIndex = searchForward(lastFindStr); } } else { lastFindIndex = lastFindIndexTemp; editor1.setCaretPosition(lastFindIndex); // ready to type in body editor1.moveCaretPosition(lastFindIndex + lastFindStr.length()); // ready to type in body } } catch (BadLocationException badexception) { String errstr = "TextViewer:searchBackward: " + badexception.getMessage(); warningPopup.display(errstr); return (-1); } return (lastFindIndex); }
/** * 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(); } }
// 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", ""); } }
/** * 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. }
/** * 将文本插入JTextPane * * @param attrib */ private void insert(FontAttrib attrib) { try { // 插入文本 doc.insertString(doc.getLength(), attrib.getText() + "\n", attrib.getAttrSet()); } catch (BadLocationException e) { e.printStackTrace(); } }
/** * 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(); } }
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; }
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(); } }
public void caretUpdate(CaretEvent e) { try { setLineCount(textArea.getLineOfOffset(e.getDot()) + 1); } catch (BadLocationException blx) { logger.warn("BadLocationException: " + blx.getMessage()); } }
/** * 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(); } }
/** * 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; } }