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:org.executequery.gui.text.TextUndoManager.java

/** Creates a new instance of TextUndoManager */
public TextUndoManager(JTextComponent textComponent) {

    this.textComponent = textComponent;
    document = textComponent.getDocument();
    document.addUndoableEditListener(this);

    // add the focus listener
    textComponent.addFocusListener(this);

    // retrieve the undo/redo actions from the cache
    undoCommand = ActionBuilder.get("undo-command");
    redoCommand = ActionBuilder.get("redo-command");

    // initialise the compound edit
    compoundEdit = new CompoundEdit();
}

From source file:org.freeplane.view.swing.features.time.mindmapmode.nodelist.NodeList.java

public NodeList(final boolean modal, final boolean showAllNodes, final boolean searchInAllMaps) {
    //      this.modeController = modeController;
    //      controller = modeController.getController();
    this.modal = modal;
    this.showAllNodes = showAllNodes;
    this.searchInAllMaps = searchInAllMaps;
    mFilterTextSearchField = new JComboBox();
    mFilterTextSearchField.setEditable(true);
    final FilterTextDocumentListener listener = new FilterTextDocumentListener();
    mFilterTextSearchField.addActionListener(listener);
    final JTextComponent editorComponent = (JTextComponent) mFilterTextSearchField.getEditor()
            .getEditorComponent();//from www.  ja  v  a  2  s  .  c  o  m
    editorComponent.getDocument().addDocumentListener(listener);
    mFilterTextSearchField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(final KeyEvent pEvent) {
            if (pEvent.getKeyCode() == KeyEvent.VK_DOWN) {
                mFilterTextReplaceField.requestFocusInWindow();
            }
        }
    });
    mFilterTextReplaceField = new JComboBox();
    mFilterTextReplaceField.setEditable(true);
    mFilterTextReplaceField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(final KeyEvent pEvent) {
            if (pEvent.getKeyCode() == KeyEvent.VK_DOWN) {
                tableView.requestFocusInWindow();
            } else if (pEvent.getKeyCode() == KeyEvent.VK_UP) {
                mFilterTextSearchField.requestFocusInWindow();
            }
        }
    });
    useRegexInReplace = new JCheckBox();
    useRegexInFind = new JCheckBox();
    useRegexInFind.addChangeListener(listener);
    matchCase = new JCheckBox();
    matchCase.addChangeListener(listener);
    final MapChangeListener mapChangeListener = new MapChangeListener();
    final ModeController modeController = Controller.getCurrentModeController();
    final MapController mapController = modeController.getMapController();
    mapController.addMapChangeListener(mapChangeListener);
    mapController.addNodeChangeListener(mapChangeListener);
    Controller.getCurrentController().getMapViewManager().addMapSelectionListener(mapChangeListener);

}

From source file:org.freeplane.view.swing.features.time.mindmapmode.NodeList.java

public NodeList(final boolean modal, final boolean showAllNodes, final boolean searchInAllMaps) {
    //      this.modeController = modeController;
    //      controller = modeController.getController();
    this.modal = modal;
    this.showAllNodes = showAllNodes;
    this.searchInAllMaps = searchInAllMaps;
    mFilterTextSearchField = new JComboBox();
    mFilterTextSearchField.setEditable(true);
    final FilterTextDocumentListener listener = new FilterTextDocumentListener();
    mFilterTextSearchField.addActionListener(listener);
    final JTextComponent editorComponent = (JTextComponent) mFilterTextSearchField.getEditor()
            .getEditorComponent();// w  w w  .  ja v  a2s. c  o m
    editorComponent.getDocument().addDocumentListener(listener);
    mFilterTextSearchField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(final KeyEvent pEvent) {
            if (pEvent.getKeyCode() == KeyEvent.VK_DOWN) {
                mFilterTextReplaceField.requestFocusInWindow();
            }
        }
    });
    mFilterTextReplaceField = new JComboBox();
    mFilterTextReplaceField.setEditable(true);
    mFilterTextReplaceField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(final KeyEvent pEvent) {
            if (pEvent.getKeyCode() == KeyEvent.VK_DOWN) {
                timeTable.requestFocusInWindow();
            } else if (pEvent.getKeyCode() == KeyEvent.VK_UP) {
                mFilterTextSearchField.requestFocusInWindow();
            }
        }
    });
    useRegexInReplace = new JCheckBox();
    useRegexInFind = new JCheckBox();
    useRegexInFind.addChangeListener(listener);
    matchCase = new JCheckBox();
    matchCase.addChangeListener(listener);
    final MapChangeListener mapChangeListener = new MapChangeListener();
    final ModeController modeController = Controller.getCurrentModeController();
    final MapController mapController = modeController.getMapController();
    mapController.addMapChangeListener(mapChangeListener);
    mapController.addNodeChangeListener(mapChangeListener);
    Controller.getCurrentController().getMapViewManager().addMapSelectionListener(mapChangeListener);

}

From source file:org.opendatakit.briefcase.ui.ScrollingStatusListDialog.java

private void appendToDocument(JTextComponent component, String msg) {
    Document doc = component.getDocument();
    try {/*from   w w  w  .  j av  a  2s . c o m*/
        doc.insertString(doc.getLength(), "\n" + msg, null);
    } catch (BadLocationException e) {
        LOG.error("Insertion failed: " + e.getMessage());
    }
}

From source file:org.paxle.desktop.impl.event.MultipleChangesListener.java

public void addComp2Monitor(final Object comp) {
    if (comp instanceof JTextComponent) {
        final JTextComponent tc = (JTextComponent) comp;
        final Document doc = tc.getDocument();
        initialValues.put(doc, new CompEntry(tc.getText()));
        doc.addDocumentListener(this);
    } else {/*from  w  ww.  j  a v  a  2  s . c  o  m*/
        final Class<?> clazz = comp.getClass();
        final int eidx = getEntryIndex(clazz);
        if (eidx < 0)
            throw new RuntimeException("component '" + clazz.getName() + "' not supported for monitoring");
        try {
            // save the initial value of the component for comparison purposes on state change
            initialValues.put(comp, new CompEntry(clazz.getMethod(GET_VALUES[eidx]).invoke(comp)));

            // register this as event listener for the component
            final Method method = clazz.getMethod("add" + ADD_LISTENERS[eidx].getSimpleName(),
                    ADD_LISTENERS[eidx]);
            method.invoke(comp, this);
            logger.debug("added " + ADD_LISTENERS[eidx].getSimpleName() + " for " + comp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.signserver.admin.gui.AddWorkerDialog.java

/** Creates new form AddWorkerDialog */
public AddWorkerDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();/*w  w w .  ja  v  a 2  s  .  co m*/

    stage = Stage.INITIAL_CONFIG;
    mode = Mode.LOAD_FROM_FILE;
    loadFromFileRadioButton.setSelected(true);
    updateControls();

    // initially set the Next button to be greyed-out, so that it can be
    // enabled based on the state
    nextApplyButton.setEnabled(false);

    invalidWorkerIdStatusLabel.setVisible(false);

    propertiesTable.setDefaultRenderer(String.class, new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean selected,
                boolean focused, int row, int column) {
            setEnabled(table == null || table.isEnabled());
            super.getTableCellRendererComponent(table, value, selected, focused, row, column);

            return this;
        }
    });

    propertiesTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(final ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                final boolean enable = propertiesTable.getSelectedRowCount() == 1;
                editPropertyButton.setEnabled(enable);
                removePropertyButton.setEnabled(enable);
            }
        }
    });

    // add a document listner to update the UI when the content of the ID
    // combobox changes
    final JTextComponent component = (JTextComponent) workerIdComboBox.getEditor().getEditorComponent();
    component.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent ev) {
            updateControls();
        }

        @Override
        public void removeUpdate(DocumentEvent ev) {
            updateControls();
        }

        @Override
        public void changedUpdate(DocumentEvent ev) {
            updateControls();
        }
    });

    // add a document listner to update the UI on updates of the configuration text
    configurationTextArea.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent ev) {
            configurationEdited = true;
            updateControls();
        }

        @Override
        public void removeUpdate(DocumentEvent ev) {
            configurationEdited = true;
            updateControls();
        }

        @Override
        public void changedUpdate(DocumentEvent ev) {
            configurationEdited = true;
            updateControls();
        }
    });
}

From source file:pl.otros.logview.gui.LogViewMainFrame.java

private void initToolbar() {
    toolBar = new JToolBar();
    final JComboBox searchMode = new JComboBox(
            new String[] { "String contains search: ", "Regex search: ", "Query search: " });
    final SearchAction searchActionForward = new SearchAction(otrosApplication, SearchDirection.FORWARD);
    final SearchAction searchActionBackward = new SearchAction(otrosApplication, SearchDirection.REVERSE);
    searchFieldCbxModel = new DefaultComboBoxModel();
    searchField = new JXComboBox(searchFieldCbxModel);
    searchField.setEditable(true);//w  w w .j a v a  2  s . c  o m
    AutoCompleteDecorator.decorate(searchField);
    searchField.setMinimumSize(new Dimension(150, 10));
    searchField.setPreferredSize(new Dimension(250, 10));
    searchField.setToolTipText(
            "<HTML>Enter text to search.<BR/>" + "Enter - search next,<BR/>Alt+Enter search previous,<BR/>"
                    + "Ctrl+Enter - mark all found</HTML>");
    final DelayedSwingInvoke delayedSearchResultUpdate = new DelayedSwingInvoke() {
        @Override
        protected void performActionHook() {
            JTextComponent editorComponent = (JTextComponent) searchField.getEditor().getEditorComponent();
            int stringEnd = editorComponent.getSelectionStart();
            if (stringEnd < 0) {
                stringEnd = editorComponent.getText().length();
            }
            try {
                String selectedText = editorComponent.getText(0, stringEnd);
                if (StringUtils.isBlank(selectedText)) {
                    return;
                }
                OtrosJTextWithRulerScrollPane<JTextPane> logDetailWithRulerScrollPane = otrosApplication
                        .getSelectedLogViewPanel().getLogDetailWithRulerScrollPane();
                MessageUpdateUtils.highlightSearchResult(logDetailWithRulerScrollPane,
                        otrosApplication.getAllPluginables().getMessageColorizers());
                RulerBarHelper.scrollToFirstMarker(logDetailWithRulerScrollPane);
            } catch (BadLocationException e) {
                LOGGER.log(Level.SEVERE, "Can't update search highlight", e);
            }
        }
    };
    JTextComponent searchFieldTextComponent = (JTextComponent) searchField.getEditor().getEditorComponent();
    searchFieldTextComponent.getDocument().addDocumentListener(new DocumentInsertUpdateHandler() {
        @Override
        protected void documentChanged(DocumentEvent e) {
            delayedSearchResultUpdate.performAction();
        }
    });
    final MarkAllFoundAction markAllFoundAction = new MarkAllFoundAction(otrosApplication);
    final SearchModeValidatorDocumentListener searchValidatorDocumentListener = new SearchModeValidatorDocumentListener(
            (JTextField) searchField.getEditor().getEditorComponent(), observer, SearchMode.STRING_CONTAINS);
    SearchMode searchModeFromConfig = configuration.get(SearchMode.class, "gui.searchMode",
            SearchMode.STRING_CONTAINS);
    final String lastSearchString;
    int selectedSearchMode = 0;
    if (searchModeFromConfig.equals(SearchMode.STRING_CONTAINS)) {
        selectedSearchMode = 0;
        lastSearchString = configuration.getString(ConfKeys.SEARCH_LAST_STRING, "");
    } else if (searchModeFromConfig.equals(SearchMode.REGEX)) {
        selectedSearchMode = 1;
        lastSearchString = configuration.getString(ConfKeys.SEARCH_LAST_REGEX, "");
    } else if (searchModeFromConfig.equals(SearchMode.QUERY)) {
        selectedSearchMode = 2;
        lastSearchString = configuration.getString(ConfKeys.SEARCH_LAST_QUERY, "");
    } else {
        LOGGER.warning("Unknown search mode " + searchModeFromConfig);
        lastSearchString = "";
    }
    Component editorComponent = searchField.getEditor().getEditorComponent();
    if (editorComponent instanceof JTextField) {
        final JTextField sfTf = (JTextField) editorComponent;
        sfTf.getDocument().addDocumentListener(searchValidatorDocumentListener);
        sfTf.getDocument().addDocumentListener(new DocumentInsertUpdateHandler() {
            @Override
            protected void documentChanged(DocumentEvent e) {
                try {
                    int length = e.getDocument().getLength();
                    if (length > 0) {
                        searchResultColorizer.setSearchString(e.getDocument().getText(0, length));
                    }
                } catch (BadLocationException e1) {
                    LOGGER.log(Level.SEVERE, "Error: ", e1);
                }
            }
        });
        sfTf.addKeyListener(new SearchFieldKeyListener(searchActionForward, sfTf));
        sfTf.setText(lastSearchString);
    }
    searchMode.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            SearchMode mode = null;
            boolean validationEnabled = false;
            String confKey = null;
            String lastSearch = ((JTextField) searchField.getEditor().getEditorComponent()).getText();
            if (searchMode.getSelectedIndex() == 0) {
                mode = SearchMode.STRING_CONTAINS;
                searchValidatorDocumentListener.setSearchMode(mode);
                validationEnabled = false;
                searchMode.setToolTipText("Checking if log message contains string (case is ignored)");
                confKey = ConfKeys.SEARCH_LAST_STRING;
            } else if (searchMode.getSelectedIndex() == 1) {
                mode = SearchMode.REGEX;
                validationEnabled = true;
                searchMode
                        .setToolTipText("Checking if log message matches regular expression (case is ignored)");
                confKey = ConfKeys.SEARCH_LAST_REGEX;
            } else if (searchMode.getSelectedIndex() == 2) {
                mode = SearchMode.QUERY;
                validationEnabled = true;
                String querySearchTooltip = "<HTML>" + //
                "Advance search using SQL-like quries (i.e. level>=warning && msg~=failed && thread==t1)<BR/>" + //
                "Valid operator for query search is ==, ~=, !=, LIKE, EXISTS, <, <=, >, >=, &&, ||, ! <BR/>" + //
                "See wiki for more info<BR/>" + //
                "</HTML>";
                searchMode.setToolTipText(querySearchTooltip);
                confKey = ConfKeys.SEARCH_LAST_QUERY;
            }
            searchValidatorDocumentListener.setSearchMode(mode);
            searchValidatorDocumentListener.setEnable(validationEnabled);
            searchActionForward.setSearchMode(mode);
            searchActionBackward.setSearchMode(mode);
            markAllFoundAction.setSearchMode(mode);
            configuration.setProperty("gui.searchMode", mode);
            searchResultColorizer.setSearchMode(mode);
            List<Object> list = configuration.getList(confKey);
            searchFieldCbxModel.removeAllElements();
            for (Object o : list) {
                searchFieldCbxModel.addElement(o);
            }
            searchField.setSelectedItem(lastSearch);
        }
    });
    searchMode.setSelectedIndex(selectedSearchMode);
    final JCheckBox markFound = new JCheckBox("Mark search result");
    markFound.setMnemonic(KeyEvent.VK_M);
    searchField.addKeyListener(markAllFoundAction);
    configuration.addConfigurationListener(markAllFoundAction);
    JButton markAllFoundButton = new JButton(markAllFoundAction);
    final JComboBox markColor = new JComboBox(MarkerColors.values());
    markFound.setSelected(configuration.getBoolean("gui.markFound", true));
    markFound.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            boolean selected = markFound.isSelected();
            searchActionForward.setMarkFound(selected);
            searchActionBackward.setMarkFound(selected);
            configuration.setProperty("gui.markFound", markFound.isSelected());
        }
    });
    markColor.setRenderer(new MarkerColorsComboBoxRenderer());
    //      markColor.addActionListener(new ActionListener() {
    //
    //         @Override
    //         public void actionPerformed(ActionEvent e) {
    //            MarkerColors markerColors = (MarkerColors) markColor.getSelectedItem();
    //            searchActionForward.setMarkerColors(markerColors);
    //            searchActionBackward.setMarkerColors(markerColors);
    //            markAllFoundAction.setMarkerColors(markerColors);
    //            configuration.setProperty("gui.markColor", markColor.getSelectedItem());
    //            otrosApplication.setSelectedMarkColors(markerColors);
    //         }
    //      });
    markColor.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            MarkerColors markerColors = (MarkerColors) markColor.getSelectedItem();
            searchActionForward.setMarkerColors(markerColors);
            searchActionBackward.setMarkerColors(markerColors);
            markAllFoundAction.setMarkerColors(markerColors);
            configuration.setProperty("gui.markColor", markColor.getSelectedItem());
            otrosApplication.setSelectedMarkColors(markerColors);
        }
    });
    markColor.getModel()
            .setSelectedItem(configuration.get(MarkerColors.class, "gui.markColor", MarkerColors.Aqua));
    buttonSearch = new JButton(searchActionForward);
    buttonSearch.setMnemonic(KeyEvent.VK_N);
    JButton buttonSearchPrev = new JButton(searchActionBackward);
    buttonSearchPrev.setMnemonic(KeyEvent.VK_P);
    enableDisableComponetsForTabs.addComponet(buttonSearch);
    enableDisableComponetsForTabs.addComponet(buttonSearchPrev);
    enableDisableComponetsForTabs.addComponet(searchField);
    enableDisableComponetsForTabs.addComponet(markFound);
    enableDisableComponetsForTabs.addComponet(markAllFoundButton);
    enableDisableComponetsForTabs.addComponet(searchMode);
    enableDisableComponetsForTabs.addComponet(markColor);
    toolBar.add(searchMode);
    toolBar.add(searchField);
    toolBar.add(buttonSearch);
    toolBar.add(buttonSearchPrev);
    toolBar.add(markFound);
    toolBar.add(markAllFoundButton);
    toolBar.add(markColor);
    JButton nextMarked = new JButton(new JumpToMarkedAction(otrosApplication, Direction.FORWARD));
    nextMarked.setToolTipText(nextMarked.getText());
    nextMarked.setText("");
    nextMarked.setMnemonic(KeyEvent.VK_E);
    enableDisableComponetsForTabs.addComponet(nextMarked);
    toolBar.add(nextMarked);
    JButton prevMarked = new JButton(new JumpToMarkedAction(otrosApplication, Direction.BACKWARD));
    prevMarked.setToolTipText(prevMarked.getText());
    prevMarked.setText("");
    prevMarked.setMnemonic(KeyEvent.VK_R);
    enableDisableComponetsForTabs.addComponet(prevMarked);
    toolBar.add(prevMarked);
    enableDisableComponetsForTabs.addComponet(toolBar.add(new SearchByLevel(otrosApplication, 1, Level.INFO)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, 1, Level.WARNING)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, 1, Level.SEVERE)));
    enableDisableComponetsForTabs.addComponet(toolBar.add(new SearchByLevel(otrosApplication, -1, Level.INFO)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, -1, Level.WARNING)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, -1, Level.SEVERE)));
}

From source file:ro.nextreports.designer.ui.sqleditor.syntax.SyntaxUtil.java

/**
 * Return the lines that span the selection (split as an array of Strings)
 * if there is no selection then current line is returned.
 * //w  w w .  j a va 2 s.c  o m
 * 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 document = (PlainDocument) target.getDocument();
        int start = document.getParagraphElement(target.getSelectionStart()).getStartOffset();
        int end;
        if (target.getSelectionStart() == target.getSelectionEnd()) {
            end = document.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 = document.getParagraphElement(target.getSelectionEnd() - 1).getEndOffset();
        }
        target.select(start, end);
        lines = document.getText(start, end - start).split("\n");
        target.select(start, end);
    } catch (BadLocationException e) {
        LOG.error(e.getMessage(), e);
        lines = EMPTY_STRING_ARRAY;
    }

    return lines;
}

From source file:ro.nextreports.designer.ui.sqleditor.syntax.SyntaxUtil.java

/**
 * Return the line of text at the document's current position.
 * /*from   w w  w  .  j a va 2  s .  c o m*/
 * @param target
 * @return
 */
public static String getLine(JTextComponent target) {
    PlainDocument document = (PlainDocument) target.getDocument();
    return getLineAt(document, target.getCaretPosition());
}