Example usage for javax.swing.text JTextComponent getDocument

List of usage examples for javax.swing.text JTextComponent getDocument

Introduction

In this page you can find the example usage for javax.swing.text JTextComponent getDocument.

Prototype

public Document getDocument() 

Source Link

Document

Fetches the model associated with the editor.

Usage

From source file:de.unentscheidbar.validation.swing.trigger.DocumentChangeTriggerTest.java

@Override
protected void provokeTrigger(Iterable<JTextComponent> components) {

    for (final JTextComponent c : components) {
        runInEdt(new Callable<Void>() {

            @Override// w  w  w  .ja v a 2 s  .  co  m
            public Void call() throws Exception {

                Document doc = c.getDocument();
                switch (rnd.nextInt(3)) {
                case 0:
                    doc.remove(doc.getStartPosition().getOffset(), doc.getLength() / 2);
                    break;
                case 1:
                    doc.insertString(rnd.nextInt(Math.max(1, doc.getStartPosition().getOffset())),
                            RandomStringUtils.randomAlphanumeric(1 + rnd.nextInt(10)), null);
                    break;
                case 2:
                    c.setText(UUID.randomUUID().toString());
                    break;
                default:
                    Assert.fail();
                }
                return null;
            }
        });

    }
    drainEventQueue();
}

From source file:com.junichi11.netbeans.php.enhancements.ui.actions.ConvertToAction.java

@Override
public void actionPerformed(ActionEvent ev) {
    try {//from   w ww  .j  av  a  2 s .com
        JTextComponent editor = EditorRegistry.lastFocusedComponent();
        if (editor == null) {
            return;
        }
        final StyledDocument document = context.openDocument();
        if (editor.getDocument() != document) {
            return;
        }

        final String selectedText = editor.getSelectedText();
        if (selectedText == null || selectedText.isEmpty()) {
            return;
        }

        final String convertedString = convert(selectedText);
        if (selectedText.equals(convertedString)) {
            return;
        }

        final int selectionStartPosition = editor.getSelectionStart();
        NbDocument.runAtomic(document, new Runnable() {

            @Override
            public void run() {
                try {
                    document.remove(selectionStartPosition, selectedText.length());
                    document.insertString(selectionStartPosition, convertedString, null);
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        });
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:DragColorTextFieldDemo.java

protected void exportDone(JComponent c, Transferable data, int action) {
    if (shouldRemove && (action == MOVE)) {
        if ((p0 != null) && (p1 != null) && (p0.getOffset() != p1.getOffset())) {
            try {
                JTextComponent tc = (JTextComponent) c;
                tc.getDocument().remove(p0.getOffset(), p1.getOffset() - p0.getOffset());
            } catch (BadLocationException e) {
                System.out.println("Can't remove text from source.");
            }/*w ww.jav  a  2 s. c o m*/
        }
    }
    source = null;
}

From source file:com.intel.stl.ui.common.view.ComponentFactory.java

public static JComboBox<String> createComboBox(String[] strArray, DocumentListener... docListeners) {

    JComboBox<String> cbox = new JComboBox<String>(strArray) {
        private static final long serialVersionUID = -7465791917624978560L;

        @Override//from  ww w .j a va 2s .  c  o  m
        public String toString() {
            return "JComboBox@" + StringUtils.intHexString(hashCode());
        }
    };
    cbox.setUI(new IntelComboBoxUI());

    // Get the text editor for this combo box
    JTextComponent tc = (JTextComponent) cbox.getEditor().getEditorComponent();

    // Initialize the document listeners
    for (DocumentListener docListener : docListeners) {
        tc.getDocument().addDocumentListener(docListener);
    }
    return cbox;
}

From source file:com.intel.stl.ui.common.view.ComponentFactory.java

public static <T> JComboBox<T> createComboBox(T[] values, JFormattedTextField textField,
        DocumentListener... docListeners) {
    JComboBox<T> cbox = new JComboBox<T>(values);
    cbox.setUI(new IntelComboBoxUI());
    FormattedComboBoxEditor editor = new FormattedComboBoxEditor(textField);
    cbox.setEditable(true);//from w w w.  jav a 2 s . c o  m
    cbox.setEditor(editor);

    // Get the text editor for this combo box
    final JTextComponent tc = (JTextComponent) cbox.getEditor().getEditorComponent();

    // Initialize the document listeners
    for (DocumentListener docListener : docListeners) {
        tc.getDocument().addDocumentListener(docListener);
    }
    return cbox;
}

From source file:com.mirth.connect.client.ui.components.rsta.ac.js.MirthSourceCompletionProvider.java

@Override
public List<Completion> getCompletionsAt(JTextComponent tc, Point p) {
    Set<Completion> completions = new HashSet<Completion>();
    List<Completion> parentCompletions = super.getCompletionsAt(tc, p);
    if (CollectionUtils.isNotEmpty(parentCompletions)) {
        completions.addAll(parentCompletions);
    }//from  w  w  w .  j a  v  a2  s .co  m

    int offset = tc.viewToModel(p);
    if (offset < 0 || offset >= tc.getDocument().getLength()) {
        lastCompletionsAtText = null;
        lastParameterizedCompletionsAt = null;
        return new ArrayList<Completion>(completions);
    }

    Segment s = new Segment();
    Document doc = tc.getDocument();
    Element root = doc.getDefaultRootElement();
    int line = root.getElementIndex(offset);
    Element elem = root.getElement(line);
    int start = elem.getStartOffset();
    int end = elem.getEndOffset() - 1;

    try {

        doc.getText(start, end - start, s);

        // Get the valid chars before the specified offset.
        int startOffs = s.offset + (offset - start) - 1;
        while (startOffs >= s.offset && Character.isLetterOrDigit(s.array[startOffs])) {
            startOffs--;
        }

        // Get the valid chars at and after the specified offset.
        int endOffs = s.offset + (offset - start);
        while (endOffs < s.offset + s.count && Character.isLetterOrDigit(s.array[endOffs])) {
            endOffs++;
        }

        int len = endOffs - startOffs - 1;
        if (len <= 0) {
            lastParameterizedCompletionsAt = null;
            return new ArrayList<Completion>(completions);
        }
        String text = new String(s.array, startOffs + 1, len);

        if (text.equals(lastCompletionsAtText)) {
            if (CollectionUtils.isNotEmpty(lastParameterizedCompletionsAt)) {
                completions.addAll(lastParameterizedCompletionsAt);
            }
            return new ArrayList<Completion>(completions);
        }

        lastCompletionsAtText = text;
        lastParameterizedCompletionsAt = completionCache.getClassCompletions(tc, text);

        if (CollectionUtils.isNotEmpty(lastParameterizedCompletionsAt)) {
            completions.addAll(lastParameterizedCompletionsAt);
        }
        return new ArrayList<Completion>(completions);

    } catch (BadLocationException ble) {
        ble.printStackTrace(); // Never happens
    }

    lastCompletionsAtText = null;
    lastParameterizedCompletionsAt = null;

    return new ArrayList<Completion>(completions);
}

From source file:de.fu_berlin.inf.dpp.netbeans.ListenerForDocumentSwap.java

/**
 * The global plug-in preferences, shared among all workspaces. Should only
 * be accessed over {@link #getGlobalPreferences()} from outside this class.
 *///ww w  . j  av a  2s.co  m
//protected Preferences configPrefs;
// private final de.fu_berlin.inf.dpp.preferences.Preferences preferences;

public ListenerForDocumentSwap() {

    sarosVersion = "13.12.6";
    ArrayList<ISarosContextFactory> factories = new ArrayList<ISarosContextFactory>();
    factories.add(new SarosNetbeansContextFactory(this));
    factories.add(new SarosCoreContextFactory());
    sarosContext = new SarosContext(factories, null);
    sarosContext.initialize();

    preferences = sarosContext.getComponent(de.fu_berlin.inf.dpp.preferences.Preferences.class);
    sarosFeatureID = PLUGIN_ID + "_" + sarosVersion; //$NON-NLS-1$
    //FeedbackPreferences.setPreferences(sarosContext
    //  .getComponent(Preferences.class));
    FeedbackPreferences.setPreferences(NbPreferences.forModule(FeedbackPanel.class));

    int favoriteColorID = new Random().nextInt(5);
    NbPreferences.forModule(SarosPanel.class).put("FAVORITE_COLOR_ID_HACK_CREATE_RANDOM_COLOR",
            Integer.toString(favoriteColorID));
    //NbPreferences.forModule(ListenerForDocumentSwap.class).put(PLUGIN_ID, "test");
    initVersionCompatibilityChart(VERSION_COMPATIBILITY_PROPERTY_FILE,
            sarosContext.getComponent(VersionManager.class));
    connectionHandler = sarosContext.getComponent(ConnectionHandler.class);
    sessionManager = sarosContext.getComponent(ISarosSessionManager.class);
    SarosPluginContext.setSarosContext(sarosContext);

    // sarosContext.getComponents(Object.class);

    isInitialized = true;
    // setDefault(this);

    /*
     * Sets up a Listener to get noticed when the first
     * file/document is selected
     * Listener then gets removed and the LookupListener takes over
     */
    initialPropertyChangeListener = new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            JTextComponent jtc = EditorRegistry.lastFocusedComponent();
            if (jtc != null) {
                Document currentDocument = jtc.getDocument();
                DataObject dataObjectForDocument = NbEditorUtilities.getDataObject(currentDocument);
                addListenerToCurrentlySelectedDocument(dataObjectForDocument);
            }
        }
    };
    EditorRegistry.addPropertyChangeListener(initialPropertyChangeListener);

    listenerForDocumentSwap = new LookupListener() {
        /*
         * The selected file in the editor changed
         * Remove the listener from the old file and/or
         * Set a listener on the new one
         * Get the relative and absolut path of the current file
         * Get the absolute path of the filecontaining project
         */
        public void resultChanged(final LookupEvent evt) {

            processDocumentSwap(evt);
        };
    };

    dataObjectOfSelectedDocument.addLookupListener(listenerForDocumentSwap);
}

From source file:com.mindcognition.mindraider.ui.swing.concept.annotation.renderer.AbstractTextAnnotationRenderer.java

/**
 * Search annotation from the current carret position.
 *//*from   ww  w  . ja va2s . c  o m*/
public void searchAnnotation(String searchString, boolean again) {
    logger.debug("searchAnnotation() " + searchString); // {{debug}}
    JTextComponent textComponent;
    if (inViewMode()) {
        textComponent = viewer;
        logger.debug("Searching viewer..."); // {{debug}}
    } else {
        textComponent = editor;
        logger.debug("Searching editor..."); // {{debug}}
    }

    if (!again) {
        textComponent.setCaretPosition(0);
    }

    if (searchString != null && searchString.length() > 0) {
        Document document = textComponent.getDocument();
        try {
            int idx = textComponent.getDocument().getText(0, document.getLength()).indexOf(searchString,
                    textComponent.getCaretPosition());
            if (idx < 0) {
                // try it from the beginning
                idx = textComponent.getDocument().getText(0, document.getLength()).indexOf(searchString);
            } else if (idx > 0) {
                textComponent.setCaretPosition(idx);
                textComponent.requestFocus();
                textComponent.select(idx, idx + searchString.length());
            }
        } catch (Exception e) {
            // TODO no bundle!
            logger.debug(Messages.getString("ConceptJPanel.unableToSearch", e.getMessage()));
        }
    }
}

From source file:ch.zhaw.iamp.rct.ui.GrammarWindow.java

private void removeTabIfPossilbe(KeyEvent event, JTextComponent component) {
    try {//w w w. j  a  v  a 2 s  .  c o m
        Document doc = component.getDocument();
        int caretPostion = component.getCaretPosition();
        int lineStartIndex = doc.getText(0, caretPostion).lastIndexOf('\n') + 1;
        lineStartIndex = lineStartIndex < 0 ? 0 : lineStartIndex;
        lineStartIndex = lineStartIndex >= doc.getLength() ? doc.getLength() - 1 : lineStartIndex;
        int scanEndIndex = lineStartIndex + 4 <= doc.getLength() ? lineStartIndex + 4 : doc.getLength();

        for (int i = 0; i < 4 && i + lineStartIndex < scanEndIndex; i++) {
            if (doc.getText(lineStartIndex, 1).matches(" ")) {
                doc.remove(lineStartIndex, 1);
            } else if (doc.getText(lineStartIndex, 1).matches("\t")) {
                doc.remove(lineStartIndex, 1);
                break;
            } else {
                break;
            }
        }

        event.consume();
    } catch (BadLocationException ex) {
        System.out.println("Could not insert a tab: " + ex.getMessage());
    }
}

From source file:ch.zhaw.iamp.rct.ui.GrammarWindow.java

private void insertTabAsSpace(KeyEvent event, JTextComponent component) {
    try {//www  .  ja  v a2  s  .c  o  m
        int caretPostion = component.getCaretPosition() - 1;
        component.getDocument().remove(caretPostion, 1);
        component.getDocument().insertString(caretPostion, "    ", null);
        event.consume();
    } catch (BadLocationException ex) {
        System.out.println("Could not insert a tab: " + ex.getMessage());
    }
}