Java Code Examples for javax.swing.text.PlainDocument

The following examples show how to use javax.swing.text.PlainDocument. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: netbeans   Source File: JWSProjectProperties.java    License: Apache License 2.0 6 votes vote down vote up
private Document createCBTextFieldDocument() {
    Document doc = new PlainDocument();
    String valueType = evaluator.getProperty(JNLP_CBASE_TYPE);
    String docString = "";
    if (CB_TYPE_LOCAL.equals(valueType)) {
        docString = getProjectDistDir();
    } else if (CB_TYPE_WEB.equals(valueType)) {
        docString = CB_URL_WEB;
    } else if (CB_TYPE_USER.equals(valueType)) {
        docString = getCodebaseLocation();
    }
    try {
        doc.insertString(0, docString, null);
    } catch (BadLocationException ex) {
        // do nothing, just return PlainDocument
        // XXX log the exc
    }
    return doc;
}
 
Example 2
Source Project: jpexs-decompiler   Source File: ActionUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Return the line of text at the given position.  The returned value may
 * be null.  It will not contain the trailing new-line character.
 * @param target the text component
 * @param pos char position
 * @return
 */
public static String getLineAt(JTextComponent target, int pos) {
	String line = null;
	Document doc = target.getDocument();
	if (doc instanceof PlainDocument) {
		PlainDocument pDoc = (PlainDocument) doc;
		int start = pDoc.getParagraphElement(pos).getStartOffset();
		int end = pDoc.getParagraphElement(pos).getEndOffset();
		try {
			line = doc.getText(start, end - start);
			if (line != null && line.endsWith("\n")) {
				line = line.substring(0, line.length() - 1);
			}
		} catch (BadLocationException ex) {
			Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
	return line;
}
 
Example 3
Source Project: netbeans   Source File: PHPTokenListTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check a token list with writing.
 *
 * @param documentContent
 * @param offset
 * @param text
 * @param startOffset
 * @param golden expected words
 * @throws Exception
 */
private void tokenListTestWithWriting(String documentContent, int offset, String text, int startOffset, String... golden) throws Exception {
    Document doc = new PlainDocument();
    doc.putProperty(Language.class, PHPTokenId.language());
    doc.insertString(0, PHPTAG + documentContent, null);
    List<String> words = new ArrayList<>();
    TokenList tokenList = new PHPTokenList(doc);
    while (tokenList.nextWord()) {
    }

    doc.insertString(offset + PHPTAG.length(), text, null);
    tokenList.setStartOffset(startOffset + PHPTAG.length());
    while (tokenList.nextWord()) {
        words.add(tokenList.getCurrentWordText().toString());
    }
    assertEquals(Arrays.asList(golden), words);
}
 
Example 4
Source Project: netbeans   Source File: HighlightingManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testExcludeTwoLayers() {
    OffsetsBag bag = new OffsetsBag(new PlainDocument());
    
    MemoryMimeDataProvider.reset(null);
    MemoryMimeDataProvider.addInstances(
        "text/plain", new SingletonLayerFactory("layer", ZOrder.DEFAULT_RACK, true, bag));

    JEditorPane pane = new JEditorPane();
    String [] removed = new String[] {"^org\\.netbeans\\.modules\\.editor\\.lib2\\.highlighting\\..*$", "^org\\.netbeans\\.modules\\.editor\\.lib2\\.highlighting\\.TextSelectionHighlighting$"};
    pane.putClientProperty("HighlightsLayerExcludes", removed);
    pane.setContentType("text/plain");
    assertEquals("The pane has got wrong mime type", "text/plain", pane.getContentType());
    
    HighlightingManager hm = HighlightingManager.getInstance(pane);
    HighlightsContainer hc = hm.getHighlights(HighlightsLayerFilter.IDENTITY);

    assertNotNull("Can't get fixed HighlightsContainer", hc);
    assertFalse("There should be no fixed highlights", hc.getHighlights(0, Integer.MAX_VALUE).moveNext());
}
 
Example 5
Source Project: consulo   Source File: ChooseByNameBase.java    License: Apache License 2.0 6 votes vote down vote up
private MyTextField() {
  super(40);
  enableEvents(AWTEvent.KEY_EVENT_MASK);
  myCompletionKeyStroke = getShortcut(IdeActions.ACTION_CODE_COMPLETION);
  forwardStroke = getShortcut(IdeActions.ACTION_GOTO_FORWARD);
  backStroke = getShortcut(IdeActions.ACTION_GOTO_BACK);
  setFocusTraversalKeysEnabled(false);
  putClientProperty("JTextField.variant", "search");
  setDocument(new PlainDocument() {
    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
      super.insertString(offs, str, a);
      if (str != null && str.length() > 1) {
        handlePaste(str);
      }
    }
  });
}
 
Example 6
Source Project: nextreports-designer   Source File: SyntaxUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return the line of text at the given position. The returned value may
 * be null. It will not contain the trailing new-line character.
 * 
 * @param doc
 * @param pos
 * @return
 */
public static String getLineAt(PlainDocument doc, int pos) {
    String line = null;
    int start = doc.getParagraphElement(pos).getStartOffset();
    int end = doc.getParagraphElement(pos).getEndOffset();
    try {
        line = doc.getText(start, end - start);
        if (line != null && line.endsWith("\n")) {
            line = line.substring(0, line.length() - 1);
        }
    } catch (BadLocationException e) {
        LOG.error(e.getMessage(), e);
    }
    
    return line;
}
 
Example 7
Source Project: netbeans   Source File: ProxyHighlightsContainerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testSimple() {
    PlainDocument doc = new PlainDocument();
    HighlightsContainer layer = createRandomBag(doc, "layer");
    HighlightsSequence highlights = layer.getHighlights(0, 100);
    
    ProxyHighlightsContainer proxyLayer = new ProxyHighlightsContainer(doc, new HighlightsContainer [] { layer });
    HighlightsSequence proxyHighlights = proxyLayer.getHighlights(0, 100);

    for ( ; highlights.moveNext(); ) {
        // Ignore empty highlights
        if (highlights.getStartOffset() == highlights.getEndOffset()) {
            continue;
        }

        assertTrue("Wrong number of proxy highlights", proxyHighlights.moveNext());

        assertEquals("Start offset does not match", highlights.getStartOffset(), proxyHighlights.getStartOffset());
        assertEquals("End offset does not match", highlights.getEndOffset(), proxyHighlights.getEndOffset());
        assertTrue("Attributes do not match", highlights.getAttributes().isEqual(proxyHighlights.getAttributes()));
    }
}
 
Example 8
Source Project: netbeans   Source File: ProxyHighlightsContainerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testEvents() {
    PlainDocument doc = new PlainDocument();
    PositionsBag hsA = new PositionsBag(doc);
    PositionsBag hsB = new PositionsBag(doc);
    
    ProxyHighlightsContainer chc = new ProxyHighlightsContainer(doc, new HighlightsContainer [] { hsA, hsB });
    Listener listener = new Listener();
    chc.addHighlightsChangeListener(listener);
    
    hsA.addHighlight(new SimplePosition(10), new SimplePosition(20), new SimpleAttributeSet());
    assertEquals("Wrong number of events", 1, listener.eventsCnt);
    assertEquals("Wrong change start offset", 10, listener.lastEventStartOffset);
    assertEquals("Wrong change end offset", 20, listener.lastEventEndOffset);

    listener.reset();
    hsB.addHighlight(new SimplePosition(11), new SimplePosition(12), new SimpleAttributeSet());
    assertEquals("Wrong number of events", 1, listener.eventsCnt);
    assertEquals("Wrong change start offset", 11, listener.lastEventStartOffset);
    assertEquals("Wrong change end offset", 12, listener.lastEventEndOffset);
}
 
Example 9
Source Project: jpexs-decompiler   Source File: ActionUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Return the lines that span the selection (split as an array of Strings)
 * if there is no selection then current line is returned.
 *
 * Note that the strings returned will not contain the terminating line feeds
 * If the document is empty, then an empty string array is returned.  So
 * you can always iterate over the returned array without a null check
 *
 * The text component will then have the full lines set as selection
 * @param target
 * @return String[] of lines spanning selection / or line containing dot
 */
public static String[] getSelectedLines(JTextComponent target) {
	String[] lines = null;
	try {
		PlainDocument pDoc = (PlainDocument) target.getDocument();
		int start = pDoc.getParagraphElement(target.getSelectionStart()).getStartOffset();
		int end;
		if (target.getSelectionStart() == target.getSelectionEnd()) {
			end = pDoc.getParagraphElement(target.getSelectionEnd()).getEndOffset();
		} else {
			// if more than one line is selected, we need to subtract one from the end
			// so that we do not select the line with the caret and no selection in it
			end = pDoc.getParagraphElement(target.getSelectionEnd() - 1).getEndOffset();
		}
		target.select(start, end);
		lines = pDoc.getText(start, end - start).split("\n");
		target.select(start, end);
	} catch (BadLocationException ex) {
		Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex);
		lines = EMPTY_STRING_ARRAY;
	}
	return lines;
}
 
Example 10
Source Project: visualvm   Source File: ActionUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the line of text at the given position.  The returned value may
 * be null.  It will not contain the trailing new-line character.
 * @param target the text component
 * @param pos char position
 * @return
 */
public static String getLineAt(JTextComponent target, int pos) {
    String line = null;
    Document doc = target.getDocument();
    if (doc instanceof PlainDocument) {
        PlainDocument pDoc = (PlainDocument) doc;
        int start = pDoc.getParagraphElement(pos).getStartOffset();
        int end = pDoc.getParagraphElement(pos).getEndOffset();
        try {
            line = doc.getText(start, end - start);
            if (line != null && line.endsWith("\n")) {
                line = line.substring(0, line.length() - 1);
            }
        } catch (BadLocationException ex) {
            Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return line;
}
 
Example 11
Source Project: netbeans   Source File: CompoundHighlightsContainerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testOrdering() {
    PlainDocument doc = new PlainDocument();
    PositionsBag hsA = new PositionsBag(doc);
    PositionsBag hsB = new PositionsBag(doc);

    SimpleAttributeSet attribsA = new SimpleAttributeSet();
    SimpleAttributeSet attribsB = new SimpleAttributeSet();
    
    attribsA.addAttribute("attribute", "value-A");
    attribsB.addAttribute("attribute", "value-B");
    
    hsA.addHighlight(new SimplePosition(5), new SimplePosition(15), attribsA);
    hsB.addHighlight(new SimplePosition(10), new SimplePosition(20), attribsB);
    
    CompoundHighlightsContainer chc = new CompoundHighlightsContainer(doc, new HighlightsContainer [] { hsA, hsB });
    HighlightsSequence highlights = chc.getHighlights(0, Integer.MAX_VALUE);

    assertTrue("Wrong number of highlights", highlights.moveNext());
    assertEquals("1. highlight - wrong attribs", "value-A", highlights.getAttributes().getAttribute("attribute"));

    assertTrue("Wrong number of highlights", highlights.moveNext());
    assertEquals("2. highlight - wrong attribs", "value-B", highlights.getAttributes().getAttribute("attribute"));

    assertTrue("Wrong number of highlights", highlights.moveNext());
    assertEquals("3. highlight - wrong attribs", "value-B", highlights.getAttributes().getAttribute("attribute"));
}
 
Example 12
Source Project: netbeans   Source File: CompoundHighlightsContainerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testConcurrentModification() throws Exception {
    PlainDocument doc = new PlainDocument();
    PositionsBag bag = createRandomBag(doc, "layer");
    HighlightsContainer [] layers = new HighlightsContainer [] { bag };
    
    CompoundHighlightsContainer hb = new CompoundHighlightsContainer(doc, layers);
    HighlightsSequence hs = hb.getHighlights(0, Integer.MAX_VALUE);
    
    assertTrue("No highlights", hs.moveNext());
    int s = hs.getStartOffset();
    int e = hs.getEndOffset();
    AttributeSet a = hs.getAttributes();

    // Change the layers
    hb.setLayers(doc, layers);
    
    assertEquals("Different startOffset", s, hs.getStartOffset());
    assertEquals("Different endOffset", e, hs.getEndOffset());
    assertEquals("Different attributes", a, hs.getAttributes());
    
    assertFalse("There should be no further highlighs after co-modification", hs.moveNext());
}
 
Example 13
Source Project: netbeans   Source File: CompoundHighlightsContainerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testEvents() {
    PlainDocument doc = new PlainDocument();
    PositionsBag hsA = new PositionsBag(doc);
    PositionsBag hsB = new PositionsBag(doc);
    
    CompoundHighlightsContainer chc = new CompoundHighlightsContainer(doc, new HighlightsContainer [] { hsA, hsB });
    Listener listener = new Listener();
    chc.addHighlightsChangeListener(listener);
    
    hsA.addHighlight(new SimplePosition(10), new SimplePosition(20), new SimpleAttributeSet());
    assertEquals("Wrong number of events", 1, listener.eventsCnt);
    assertEquals("Wrong change start offset", 10, listener.lastEventStartOffset);
    assertEquals("Wrong change end offset", 20, listener.lastEventEndOffset);

    listener.reset();
    hsB.addHighlight(new SimplePosition(11), new SimplePosition(12), new SimpleAttributeSet());
    assertEquals("Wrong number of events", 1, listener.eventsCnt);
    assertEquals("Wrong change start offset", 11, listener.lastEventStartOffset);
    assertEquals("Wrong change end offset", 12, listener.lastEventEndOffset);
}
 
Example 14
Source Project: netbeans   Source File: CompoundHighlightsContainerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testEvents2() {
    PlainDocument doc = new PlainDocument();
    PositionsBag hsA = new PositionsBag(doc);
    PositionsBag hsB = new PositionsBag(doc);

    hsA.addHighlight(new SimplePosition(10), new SimplePosition(20), new SimpleAttributeSet());
    hsB.addHighlight(new SimplePosition(11), new SimplePosition(12), new SimpleAttributeSet());

    CompoundHighlightsContainer chc = new CompoundHighlightsContainer();
    Listener listener = new Listener();
    chc.addHighlightsChangeListener(listener);

    // changing delegate layers fires event covering 'all' offsets
    chc.setLayers(doc, new HighlightsContainer [] { hsA, hsB });
    assertEquals("Wrong number of events", 1, listener.eventsCnt);
    assertEquals("Wrong change start offset", 0, listener.lastEventStartOffset);
    assertEquals("Wrong change end offset", Integer.MAX_VALUE, listener.lastEventEndOffset);
}
 
Example 15
Source Project: netbeans   Source File: CompoundHighlightsContainerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testZeroPosition() throws BadLocationException {
    PlainDocument doc = new PlainDocument();
    TestHighlighsContainer thc = new TestHighlighsContainer();
    CompoundHighlightsContainer chc = new CompoundHighlightsContainer();

    chc.setLayers(doc, new HighlightsContainer[] { thc });
    doc.insertString(0, "0123456789", null);

    chc.getHighlights(0, Integer.MAX_VALUE);
    assertEquals("Should have been queried", 2, thc.queries.size());
    assertEquals("Wrong query startOffset", 0, (int) thc.queries.get(0));

    thc.queries.clear();
    doc.insertString(0, "abcd", null);
    assertEquals("Should not have been queried", 0, thc.queries.size());

    chc.getHighlights(0, Integer.MAX_VALUE);
    assertEquals("Should have been queried again", 2, thc.queries.size());
    assertEquals("Wrong query startOffset", 0, (int) thc.queries.get(0));

    thc.queries.clear();
    chc.getHighlights(0, Integer.MAX_VALUE);
    assertEquals("Should not have been queried again", 0, thc.queries.size());
}
 
Example 16
Source Project: netbeans   Source File: WordMatchTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testOffset0Forward() throws Exception {
    Document doc = new PlainDocument();
    WordMatch wordMatch = WordMatch.get(doc);
    //                   012345678901234567890123456789
    doc.insertString(0, "abc abc dab ab a abab+c", null);
    int docLen = doc.getLength();
    wordMatch.matchWord(0, true);
    compareText(doc, 0, "abca", docLen + 3);
    wordMatch.matchWord(0, true);
    compareText(doc, 0, "daba", docLen + 3);
    wordMatch.matchWord(0, true);
    compareText(doc, 0, "aba", docLen + 2);
    wordMatch.matchWord(0, true);
    compareText(doc, 0, "aa", docLen + 1);
    wordMatch.matchWord(0, true);
    compareText(doc, 0, "ababa", docLen + 4);
    wordMatch.matchWord(0, true);
    compareText(doc, 0, "ca", docLen + 1);
    wordMatch.matchWord(0, true);
    compareText(doc, 0, "ca", docLen + 1);

    wordMatch.matchWord(0, false);
    compareText(doc, 0, "ababa", docLen + 4);
}
 
Example 17
Source Project: netbeans   Source File: WordMatchTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testOffsetDocLenBackward() throws Exception {
    Document doc = new PlainDocument();
    WordMatch wordMatch = WordMatch.get(doc);
    //                   012345678901234567890123456789
    doc.insertString(0, "abc abc dab ab a", null);
    int docLen = doc.getLength();
    wordMatch.matchWord(docLen, false);
    compareText(doc, docLen - 1, "ab", docLen + 1);
    wordMatch.matchWord(docLen, false);
    compareText(doc, docLen - 1, "abc", docLen + 2);
    wordMatch.matchWord(docLen, false);
    compareText(doc, docLen - 1, "abc", docLen + 2);

    wordMatch.matchWord(docLen, true);
    compareText(doc, docLen - 1, "ab", docLen + 1);
    wordMatch.matchWord(docLen, true);
    compareText(doc, docLen - 1, "a", docLen);
}
 
Example 18
Source Project: visualvm   Source File: UnindentAction.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void actionPerformed(ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    Integer tabStop = (Integer) target.getDocument().getProperty(PlainDocument.tabSizeAttribute);
    String indent = ActionUtils.SPACES.substring(0, tabStop);
    if (target != null) {
        String[] lines = ActionUtils.getSelectedLines(target);
        int start = target.getSelectionStart();
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            if (line.startsWith(indent)) {
                sb.append(line.substring(indent.length()));
            } else if (line.startsWith("\t")) {
                sb.append(line.substring(1));
            } else {
                sb.append(line);
            }
            sb.append('\n');
        }
        target.replaceSelection(sb.toString());
        target.select(start, start + sb.length());
    }
}
 
Example 19
Source Project: netbeans   Source File: PlainDocumentTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testCuriosities() throws Exception {
    // Test position at offset 0 does not move after insert
    Document doc = new PlainDocument();
    doc.insertString(0, "test", null);
    Position pos = doc.createPosition(0);
    assertEquals(0, pos.getOffset());
    doc.insertString(0, "a", null);
    assertEquals(0, pos.getOffset());
    
    // Test there is an extra newline above doc.getLength()
    assertEquals("\n", doc.getText(doc.getLength(), 1));
    assertEquals("atest\n", doc.getText(0, doc.getLength() + 1));
    
    // Test the last line element contains the extra newline
    Element lineElem = doc.getDefaultRootElement().getElement(0);
    assertEquals(0, lineElem.getStartOffset());
    assertEquals(doc.getLength() + 1, lineElem.getEndOffset());

    // Test that once position gets to zero it won't go anywhere else (unless undo performed)
    pos = doc.createPosition(1);
    doc.remove(0, 1);
    assertEquals(0, pos.getOffset());
    doc.insertString(0, "b", null);
    assertEquals(0, pos.getOffset());
}
 
Example 20
Source Project: visualvm   Source File: ActionUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the lines that span the selection (split as an array of Strings)
 * if there is no selection then current line is returned.
 * 
 * Note that the strings returned will not contain the terminating line feeds
 * 
 * The text component will then have the full lines set as selection
 * @param target
 * @return String[] of lines spanning selection / or Dot
 */
public static String[] getSelectedLines(JTextComponent target) {
    String[] lines = null;
    try {
        PlainDocument pDoc = (PlainDocument) target.getDocument();
        int start = pDoc.getParagraphElement(target.getSelectionStart()).getStartOffset();
        int end;
        if (target.getSelectionStart() == target.getSelectionEnd()) {
            end = pDoc.getParagraphElement(target.getSelectionEnd()).getEndOffset();
        } else {
            // if more than one line is selected, we need to subtract one from the end
            // so that we do not select the line with the caret and no selection in it
            end = pDoc.getParagraphElement(target.getSelectionEnd() - 1).getEndOffset();
        }
        target.select(start, end);
        lines = pDoc.getText(start, end - start).split("\n");
        target.select(start, end);
    } catch (BadLocationException ex) {
        Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex);
        lines = EMPTY_STRING_ARRAY;
    }
    return lines;
}
 
Example 21
Source Project: netbeans   Source File: PositionsBagRandomTest.java    License: Apache License 2.0 6 votes vote down vote up
private PositionsBag mergeContainers(boolean merge, String [] layerNames, HighlightsContainer[] containers) {
    PositionsBag bag = new PositionsBag(new PlainDocument(), merge);

    for (int i = 0; i < containers.length; i++) {
        HighlightsSequence layerHighlights = 
            containers[i].getHighlights(START, END);
        
        for ( ; layerHighlights.moveNext(); ) {
            bag.addHighlight(
                new SimplePosition(layerHighlights.getStartOffset()), 
                new SimplePosition(layerHighlights.getEndOffset()), 
                layerHighlights.getAttributes());
        }
    }
    
    return bag;
}
 
Example 22
Source Project: netbeans   Source File: ComplexPositionsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPos() throws Exception {
    Document doc = new PlainDocument();
    doc.insertString(0, "\t\t\n\n", null);
    Position pos1 = doc.createPosition(1);
    Position pos2 = doc.createPosition(2);
    
    Position pos10 = ComplexPositions.create(pos1, 0);
    Position pos11 = ComplexPositions.create(pos1, 1);
    Position pos20 = ComplexPositions.create(pos2, 0);
    Position pos21 = ComplexPositions.create(pos2, 1);
    
    assertEquals(0, ComplexPositions.getSplitOffset(pos1));
    assertEquals(0, ComplexPositions.getSplitOffset(pos10));
    assertEquals(1, ComplexPositions.getSplitOffset(pos11));
    comparePos(pos1, pos10, 0);
    comparePos(pos10, pos11, -1);
    comparePos(pos1, pos2, -1);
    comparePos(pos10, pos20, -1);
    comparePos(pos20, pos21, -1);
}
 
Example 23
Source Project: netbeans   Source File: DocumentUtilitiesTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testAddWeakPropertyChangeListenerSupported() {
    SampleListener sl = new SampleListener();
    // This simulates the construction of the BaseDocument
    PlainDocument pd = new PlainDocument();
    PropertyChangeSupport pcs = new PropertyChangeSupport(pd);
    pd.putProperty(PropertyChangeSupport.class, pcs);

    PropertyChangeListener weakListener = DocumentUtilities.addWeakPropertyChangeListener(pd, sl);
    // A PropertyChangeListener added through addWeakPropertyChangeListener
    // to a PropertyChangeListener supporting document, must be reflected
    // in a non-null return value
    assertNotNull(weakListener);

    // the backing listner needs to be invoked when a property is changed
    pcs.firePropertyChange("demoProperty", null, "demoValue");
    assertEquals(1, sl.getCallCount("demoProperty"));

    // The returned Listner must be usable for listener removal
    DocumentUtilities.removePropertyChangeListener(pd, weakListener);
    sl.reset();
    pcs.firePropertyChange("demoProperty", null, "demoValue");
    assertEquals(0, sl.getCallCount("demoProperty"));

}
 
Example 24
Source Project: nextreports-designer   Source File: SyntaxDocument.java    License: Apache License 2.0 6 votes vote down vote up
public SyntaxDocument(Lexer lexer) {
    super();
    putProperty(PlainDocument.tabSizeAttribute, 4); // outside ?!
    this.lexer = lexer;
    
    // Listen for undo and redo events
    addUndoableEditListener(new UndoableEditListener() {

        public void undoableEditHappened(UndoableEditEvent event) {
            if (event.getEdit().isSignificant()) {
                undo.addEdit(event.getEdit());
            }
        }
        
    });
}
 
Example 25
Source Project: openAGV   Source File: StringPropertyCellEditor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Component getTableCellEditorComponent(
    JTable table, Object value, boolean isSelected, int row, int column) {

  setValue(value);
  JTextField textField = (JTextField) getComponent();
  if (value instanceof StringProperty) {
    textField.setDocument(new PlainDocument());
  }
  textField.setText(property().getText());

  return fComponent;
}
 
Example 26
Source Project: netbeans   Source File: ReindenterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    doc = new PlainDocument();
    doc.putProperty("mimeType", "text/x-java");
    doc.putProperty(Language.class, JavaTokenId.language());
}
 
Example 27
Source Project: netbeans   Source File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
public static Map<String, String> setCodePreferences(Map<String, String> values) {
    Preferences preferences = CodeStylePreferences.get(new PlainDocument(), JavacParser.MIME_TYPE).getPreferences();
    Map<String, String> origValues = new HashMap<String, String>();
    for (String key : values.keySet()) {
        origValues.put(key, preferences.get(key, null));
    }
    setValues(preferences, values);

    return origValues;
}
 
Example 28
Source Project: netbeans   Source File: JavaTokenListTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testPositions() throws Exception {
    Document doc = new PlainDocument();
    
    doc.putProperty(Language.class, JavaTokenId.language());
    
    doc.insertString(0, "/**tes test <pre>testt</pre> <a href='testtt'>testttt</a> testttttt*/", null);
    
    TokenList l = new JavaTokenList(doc);
    
    l.setStartOffset(9);
    assertTrue(l.nextWord());
    assertEquals(7, l.getCurrentWordStartOffset());
    assertTrue("test".equals(l.getCurrentWordText().toString()));
}
 
Example 29
Source Project: netbeans   Source File: OutputPane.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void setDocument (Document doc) {
    if (doc == null) {
        Document d = getDocument();
        if (d != null) {
            d.removeDocumentListener(this);
        }
        textView.setDocument (new PlainDocument());
        return;
    }
    textView.setEditorKit(new OutputEditorKit(isWrapped(), textView,
            editorKitListener));
    super.setDocument(doc);
    updateKeyBindings();
}
 
Example 30
Source Project: netbeans   Source File: CustomizerDataSupport.java    License: Apache License 2.0 5 votes vote down vote up
/** Create a Document initialized by the specified text parameter, which may be null */
private Document createDocument(String text) {
    PlainDocument doc = new PlainDocument();
    if (text != null) {
        try {
            doc.insertString(0, text, null);
        } catch(BadLocationException e) {
            Exceptions.printStackTrace(e);
        }
    }
    return doc;
}