Java Code Examples for javax.swing.text.JTextComponent

The following are top voted examples for showing how to use javax.swing.text.JTextComponent. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: BaseKit.java   Source Code and License 6 votes vote down vote up
public void actionPerformed(final ActionEvent evt, final JTextComponent target) {
    if (target != null) {
        final Caret caret = target.getCaret();
        final BaseDocument doc = (BaseDocument)target.getDocument();
        doc.render(new Runnable () {
            public void run () {
                DocumentUtilities.setTypingModification(doc, true);
                try {
                    int dotPos = caret.getDot();
                    int bolPos = Utilities.getRowStart(target, dotPos);
                    int eolPos = Utilities.getRowEnd(target, dotPos);
                    eolPos = Math.min(eolPos + 1, doc.getLength()); // include '\n'
                    caret.setDot(bolPos);
                    caret.moveDot(eolPos);
                } catch (BadLocationException e) {
                    target.getToolkit().beep();
                } finally {
                    DocumentUtilities.setTypingModification(doc, false);
                }
            }
        });
    }
}
 
Example 2
Project: incubator-netbeans   File: EditorUI.java   Source Code and License 6 votes vote down vote up
public void showPopupMenu(int x, int y) {
    // First call the build-popup-menu action to possibly rebuild the popup menu
    JTextComponent c = getComponent();
    if (c != null) {
        BaseKit kit = Utilities.getKit(c);
        if (kit != null) {
            Action a = kit.getActionByName(ExtKit.buildPopupMenuAction);
            if (a != null) {
                a.actionPerformed(new ActionEvent(c, 0, "")); // NOI18N
            }
        }

        JPopupMenu pm = getPopupMenu();
        if (pm != null) {
            if (c.isShowing()) { // fix of #18808
                if (!c.isFocusOwner()) {
                    c.requestFocus();
                }
                pm.show(c, x, y);
            }
        }
    }
}
 
Example 3
Project: enigma-vk   File: BoxHighlightPainter.java   Source Code and License 6 votes vote down vote up
@Override
public void paint(Graphics g, int start, int end, Shape shape, JTextComponent text) {
	Rectangle bounds = getBounds(text, start, end);
	
	// fill the area
	if (m_fillColor != null) {
		g.setColor(m_fillColor);
		g.fillRoundRect(bounds.x, bounds.y, bounds.width, bounds.height, 4, 4);
	}
	
	// draw a box around the area
	g.setColor(m_borderColor);
	g.drawRoundRect(bounds.x, bounds.y, bounds.width, bounds.height, 4, 4);
}
 
Example 4
Project: incubator-netbeans   File: Editor.java   Source Code and License 6 votes vote down vote up
private boolean saveAs( Component comp ) {
    if( comp == null ) return false;
    JTextComponent edit = (JTextComponent)com2text.get( comp );
    File file = (File)edit.getDocument().getProperty( FILE );
    
    fileChooser.setCurrentDirectory( file.getParentFile() );
    fileChooser.setSelectedFile( file );
    KitInfo fileInfo = KitInfo.getKitInfoOrDefault( file );
    
    if( fileInfo != null ) fileChooser.setFileFilter( fileInfo );
    
    // show the dialog, test the result
    if( fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
        return saveFile( comp, fileChooser.getSelectedFile(), true );
    else
        return false; // Cancel was pressed - not saved
}
 
Example 5
Project: incubator-netbeans   File: ComponentUtils.java   Source Code and License 6 votes vote down vote up
public static void setStatusText(JTextComponent c, String text) {
        // TODO: fix this, do not use reflection
        try {
            Object editorUI = getEditorUI(c);
            if (editorUI == null) {
                c.putClientProperty(STATUS_BAR_TEXT_PROPERTY, text);
                return;
            }
            Method getSbMethod = editorUI.getClass().getMethod("getStatusBar");
            Object statusBar = getSbMethod.invoke(editorUI);
            Method setTextMethod = statusBar.getClass().getMethod("setText", String.class, String.class);
            setTextMethod.invoke(statusBar, "main", text);
        } catch (Exception e) {
            LOG.log(Level.WARNING, e.getMessage(), e);
        }
//        StatusBar sb = getEditorUI(c).getStatusBar();
//        if (sb != null) {
//            sb.setText(StatusBar.CELL_MAIN, text);
//        }
    }
 
Example 6
Project: incubator-netbeans   File: JavadocCompletionItem.java   Source Code and License 6 votes vote down vote up
public void defaultAction(JTextComponent component) {
    if (component != null) {
        Completion.get().hideDocumentation();
        Completion.get().hideCompletion();
        
        StringBuilder sb = new StringBuilder();
        sb.append(this.name);
        if (this.paramTypes.length == 0) {
            sb.append("() "); // NOI18N
        } else {
            sb.append('(');
            for (String pt : paramTypes) {
                sb.append(pt).append(", "); // NOI18N
            }
            sb.setCharAt(sb.length() - 2, ')');
        }
        
        complete(component, sb.toString(), substitutionOffset);
    }
}
 
Example 7
Project: incubator-netbeans   File: GlyphGutter.java   Source Code and License 6 votes vote down vote up
private int getLineFromMouseEvent(MouseEvent e){
    int line = -1;
    EditorUI eui = editorUI;
    if (eui != null) {
        try{
            JTextComponent component = eui.getComponent();
            BaseDocument document = eui.getDocument();
            BaseTextUI textUI = (BaseTextUI)component.getUI();
            int clickOffset = textUI.viewToModel(component, new Point(0, e.getY()));
            line = Utilities.getLineOffset(document, clickOffset);
        }catch (BadLocationException ble) {
            LOG.log(Level.WARNING, null, ble);
        }
    }
    return line;
}
 
Example 8
Project: incubator-netbeans   File: MasterMatcher.java   Source Code and License 6 votes vote down vote up
private MasterMatcher(JTextComponent component) {
    this.component = component;
    if (component != null) {
        component.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if ("document".equals(evt.getPropertyName())) {
                    synchronized (LOCK) {
                        // Cancel any pending task and clear the lastResult
                        if (task != null) {
                            task.cancel();
                            task = null;
                        }
                        if (lastResult != null) {
                            lastResult.cancel();
                            lastResult = null; // Prevent memory leak upon document change
                        }
                    }
                }
            }
        });
    }
}
 
Example 9
Project: incubator-netbeans   File: GsfCompletionItem.java   Source Code and License 6 votes vote down vote up
@Override
public boolean instantSubstitution(JTextComponent component) {
    ElementKind kind = item.getKind();
    if (kind == ElementKind.PARAMETER || kind == ElementKind.CLASS || kind == ElementKind.MODULE) {
        // These types of elements aren't ever instant substituted in Java - use same behavior here
        return false;
    }

    if (component != null) {
        try {
            int caretOffset = component.getSelectionEnd();
            if (caretOffset > substitutionOffset) {
                String text = component.getDocument().getText(substitutionOffset, caretOffset - substitutionOffset);
                if (!getInsertPrefix().toString().startsWith(text)) {
                    return false;
                }
            }
        }
        catch (BadLocationException ble) {}
    }
    defaultAction(component);
    return true;
}
 
Example 10
Project: OpenJSharp   File: CAccessibleText.java   Source Code and License 6 votes vote down vote up
static int[] getVisibleCharacterRange(final Accessible a) {
    final Accessible sa = CAccessible.getSwingAccessible(a);
    if (!(sa instanceof JTextComponent)) return null;

    final JTextComponent jc = (JTextComponent) sa;
    final Rectangle rect = jc.getVisibleRect();
    final Point topLeft = new Point(rect.x, rect.y);
    final Point topRight = new Point(rect.x + rect.width, rect.y);
    final Point bottomLeft = new Point(rect.x, rect.y + rect.height);
    final Point bottomRight = new Point(rect.x + rect.width, rect.y + rect.height);

    int start = Math.min(jc.viewToModel(topLeft), jc.viewToModel(topRight));
    int end = Math.max(jc.viewToModel(bottomLeft), jc.viewToModel(bottomRight));
    if (start < 0) start = 0;
    if (end < 0) end = 0;
    return new int[] { start, end };
}
 
Example 11
Project: incubator-netbeans   File: AnnotationViewDataImpl.java   Source Code and License 6 votes vote down vote up
public void register(BaseDocument document) {
    this.document = document;
    
    JTextComponent pane = paneRef.get();
    if (pane != null) {
        gatherProviders(pane);
    }
    
    if (document != null) {
        if (weakL == null) {
            weakL = WeakListeners.create(Annotations.AnnotationsListener.class, this, document.getAnnotations());
            document.getAnnotations().addAnnotationsListener(weakL);
        }
    }
    
    clear();
}
 
Example 12
Project: openjdk-jdk10   File: TextComponentPrintable.java   Source Code and License 6 votes vote down vote up
/**
 * Constructs  {@code TextComponentPrintable} to print {@code JTextComponent}
 * {@code textComponent} with {@code headerFormat} and {@code footerFormat}.
 *
 * @param textComponent {@code JTextComponent} to print
 * @param headerFormat the page header or {@code null} for none
 * @param footerFormat the page footer or {@code null} for none
 */
private TextComponentPrintable(JTextComponent textComponent,
        MessageFormat headerFormat,
        MessageFormat footerFormat) {
    this.textComponentToPrint = textComponent;
    this.headerFormat = headerFormat;
    this.footerFormat = footerFormat;
    headerFont = textComponent.getFont().deriveFont(Font.BOLD,
        HEADER_FONT_SIZE);
    footerFont = textComponent.getFont().deriveFont(Font.PLAIN,
        FOOTER_FONT_SIZE);
    this.pagesMetrics =
        Collections.synchronizedList(new ArrayList<IntegerSegment>());
    this.rowsMetrics = new ArrayList<IntegerSegment>(LIST_SIZE);
    this.printShell = createPrintShell(textComponent);
}
 
Example 13
Project: incubator-netbeans   File: RevertModifications.java   Source Code and License 6 votes vote down vote up
private void initInputVerifiers () {
    InputVerifier iv = new InputVerifier() {
        @Override
        public boolean verify (JComponent input) {
            if (input == panel.startRevisionTextField || input == panel.endRevisionTextField || input == panel.oneRevisionTextField) {
                JTextComponent comp = (JTextComponent) input;
                if (comp.getText().trim().isEmpty()) {
                    comp.setText(SVNRevision.HEAD.toString());
                }
            }
            return true;
        }
    };
    panel.startRevisionTextField.setInputVerifier(iv);
    panel.endRevisionTextField.setInputVerifier(iv);
    panel.oneRevisionTextField.setInputVerifier(iv);
}
 
Example 14
Project: incubator-netbeans   File: OverrideEditorActions.java   Source Code and License 6 votes vote down vote up
protected boolean delegates(JTextComponent target) {
    ConsoleModel model = ConsoleModel.get(target.getDocument());
    if (model == null) {
        return true;
    }
    ConsoleSection input = model.getInputSection();
    if (input == null) {
        return true;
    }
    int offset = target.getCaretPosition();
    if (offset < input.getPartBegin() || offset > input.getEnd()) {
        return true;
    }
    Document doc = target.getDocument();
    
    LineDocument ld = LineDocumentUtils.as(doc, LineDocument.class);
    if (ld == null) {
        return true;
    }
    try {
        int end = LineDocumentUtils.getLineEnd(ld, input.getPartBegin());
        return offset > end;
    } catch (BadLocationException ex) {
        return true;
    }
}
 
Example 15
Project: incubator-netbeans   File: FoldHierarchyTransactionImpl.java   Source Code and License 6 votes vote down vote up
public FoldHierarchyTransactionImpl(FoldHierarchyExecution execution, boolean suppressEvents) {
    this.execution = execution;
    this.affectedStartOffset = -1;
    this.affectedEndOffset = -1;
    this.suppressEvents = suppressEvents;
    
    this.transaction = SpiPackageAccessor.get().createFoldHierarchyTransaction(this);
    this.dmgCounter = execution.getDamagedCount();
    if (dmgCounter > 0) {
        String t = null;
        JTextComponent comp = execution.getComponent();
        if (comp != null) {
            Document doc = comp.getDocument();
            try {
                t = doc.getText(0, doc.getLength());
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
        if (debugFoldHierarchy) {
            initialSnapshot = execution.toString() + 
                              "\nContent at previous commit:\n====\n" + execution.getCommittedContent() + "\n====\n" +
                              "\nText content:\n====\n" + t + "\n====\n";
        }
    }
}
 
Example 16
Project: incubator-netbeans   File: GoToSuperTypeAction.java   Source Code and License 6 votes vote down vote up
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    final JavaSource js = JavaSource.forDocument(target.getDocument());
    
    if (js == null) {
        StatusDisplayer.getDefault().setStatusText(NbBundle.getMessage(GoToSupport.class, "WARN_CannotGoToGeneric",1));
        return;
    }
    
    final int caretPos = target.getCaretPosition();
    final AtomicBoolean cancel = new AtomicBoolean();
    
    ProgressUtils.runOffEventDispatchThread(new Runnable() {
        @Override
        public void run() {
            goToImpl(target, js, caretPos, cancel);
        }
    }, NbBundle.getMessage(JavaKit.class, "goto-super-implementation"), cancel, false);
}
 
Example 17
Project: incubator-netbeans   File: EndTagResultItem.java   Source Code and License 6 votes vote down vote up
private void reindent(JTextComponent component) {
    final BaseDocument doc = (BaseDocument) component.getDocument();
    final int dotPos = component.getCaretPosition();
    final Indent indent = Indent.get(doc);
    indent.lock();
    try {
        doc.runAtomic(new Runnable() {

            @Override
            public void run() {
                try {
                    int startOffset = Utilities.getRowStart(doc, dotPos);
                    int endOffset = Utilities.getRowEnd(doc, dotPos);
                    indent.reindent(startOffset, endOffset);
                } catch (BadLocationException ex) {
                    //ignore
                    }
            }
        });
    } finally {
        indent.unlock();
    }

}
 
Example 18
Project: incubator-netbeans   File: CamelCaseOperations.java   Source Code and License 6 votes vote down vote up
static int previousCamelCasePosition(JTextComponent textComponent) {
    int offset = textComponent.getCaretPosition();

    // Are we at the beginning of the document?
    if (offset == 0) {
        return -1;
    }

    final Document doc = textComponent.getDocument();
    
    KeystrokeHandler bc = UiUtils.getBracketCompletion(doc, offset);
    if (bc != null) {
        int nextOffset = bc.getNextWordOffset(
                doc, offset, true);
        if (nextOffset != -1) {
            return nextOffset;
        }
    }
    
    try {
        return Utilities.getPreviousWord(textComponent, offset);
    } catch (BadLocationException ble) {
        ErrorManager.getDefault().notify(ble);
    }
    return -1;
}
 
Example 19
Project: incubator-netbeans   File: Registry.java   Source Code and License 6 votes vote down vote up
/** Get the iterator over the active documents. It starts with
 * the most active document till the least active document.
 * It's just the current snapshot so the iterator will
 * not reflect future changes.
 */
public static Iterator<? extends Document> getDocumentIterator() {
    registerListener();
    final Iterator<? extends JTextComponent> cIt = getComponentIterator();
    return new Iterator<Document>() {
        public boolean hasNext() {
            return cIt.hasNext();
        }

        public Document next() {
            return cIt.next().getDocument();
        }

        public void remove() {
            cIt.remove();
        }
    };
}
 
Example 20
Project: incubator-netbeans   File: AnnotationBar.java   Source Code and License 6 votes vote down vote up
/**
 * Creates new instance initializing final fields.
 */
public AnnotationBar(JTextComponent target) {
    this.textComponent = target;
    this.editorUI = Utilities.getEditorUI(target);
    this.foldHierarchy = FoldHierarchy.get(editorUI.getComponent());
    this.doc = editorUI.getDocument();
    setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
    elementAnnotationsSubstitute = "";                              //NOI18N
    if (textComponent instanceof JEditorPane) {
        String mimeType = org.netbeans.lib.editor.util.swing.DocumentUtilities.getMimeType(textComponent);
        FontColorSettings fcs = MimeLookup.getLookup(mimeType).lookup(FontColorSettings.class);
        renderingHints = (Map) fcs.getFontColors(FontColorNames.DEFAULT_COLORING).getAttribute(EditorStyleConstants.RenderingHints);
    } else {
        renderingHints = null;
    }
}
 
Example 21
Project: incubator-netbeans   File: Utilities.java   Source Code and License 6 votes vote down vote up
/**
 * Fetches the text component that currently has focus. It delegates to 
 * TextAction.getFocusedComponent().
 * @return the component
 */
public static JTextComponent getFocusedComponent() {
    /** Fake action for getting the focused component */
    class FocusedComponentAction extends TextAction {
        
        FocusedComponentAction() {
            super("focused-component"); // NOI18N
        }
        
        /** adding this method because of protected final getFocusedComponent */
        JTextComponent getFocusedComponent2() {
            return getFocusedComponent();
        }
        
        public @Override void actionPerformed(ActionEvent evt){}
    }
    
    if (focusedComponentAction == null) {
        focusedComponentAction = new FocusedComponentAction();
    }
    
    return ((FocusedComponentAction)focusedComponentAction).getFocusedComponent2();
}
 
Example 22
Project: incubator-netbeans   File: InsertSemicolonAction.java   Source Code and License 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    if (!target.isEditable() || !target.isEnabled()) {
        target.getToolkit().beep();
        return;
    }
    final BaseDocument doc = (BaseDocument) target.getDocument();
    final Indent indenter = Indent.get(doc);
    final class R implements Runnable {
        public @Override void run() {
            try {
                Caret caret = target.getCaret();
                int dotpos = caret.getDot();
                int eoloffset = Utilities.getRowEnd(target, dotpos);
                doc.insertString(eoloffset, "" + what, null); //NOI18N
                if (withNewline) {
                    //This is code from the editor module, but it is
                    //a pretty strange way to do this:
                    doc.insertString(dotpos, "-", null); //NOI18N
                    doc.remove(dotpos, 1);
                    int eolDot = Utilities.getRowEnd(target, caret.getDot());
                    int newDotPos = indenter.indentNewLine(eolDot);
                    caret.setDot(newDotPos);
                }
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
    indenter.lock();
    try {
        doc.runAtomicAsUser(new R());
    } finally {
        indenter.unlock();
    }
}
 
Example 23
Project: openjdk-jdk10   File: AquaTextFieldSearch.java   Source Code and License 5 votes vote down vote up
static void updateCancelIcon(final JButton button, final JTextComponent text) {
    if (SwingUtilities.isEventDispatchThread()) {
        updateCancelIconOnEDT(button, text);
    } else {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() { updateCancelIconOnEDT(button, text); }
        });
    }
}
 
Example 24
Project: incubator-netbeans   File: AnnotationViewDataImpl.java   Source Code and License 5 votes vote down vote up
private static void createMarkProviders(Collection<? extends MarkProviderCreator> creators, List<MarkProvider> providers, JTextComponent pane) {
    for (MarkProviderCreator creator : creators) {
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("creator = " + creator);
        }

        MarkProvider provider = creator.createMarkProvider(pane);
        if (provider != null) {
            providers.add(provider);
        }
    }
}
 
Example 25
Project: incubator-netbeans   File: WordCompletion.java   Source Code and License 5 votes vote down vote up
public CompletionTask createTask(int queryType, JTextComponent component) {
    if (queryType == COMPLETION_QUERY_TYPE) {
        return new AsyncCompletionTask(new Query(), component);
    }
    
    return null;
}
 
Example 26
Project: powertext   File: ParameterizedCompletionContext.java   Source Code and License 5 votes vote down vote up
/**
 * Removes the bounding boxes around parameters.
 */
private void removeParameterHighlights() {
	JTextComponent tc = ac.getTextComponent();
	Highlighter h = tc.getHighlighter();
	for (int i=0; i<tags.size(); i++) {
		h.removeHighlight(tags.get(i));
	}
	tags.clear();
	for (ParamCopyInfo pci : paramCopyInfos) {
		h.removeHighlight(pci.h);
	}
	paramCopyInfos.clear();
}
 
Example 27
Project: incubator-netbeans   File: IsOverriddenAnnotationAction.java   Source Code and License 5 votes vote down vote up
private static void mouseClicked(Map<String, List<OverrideDescription>> caption2Descriptions, JTextComponent c, Point p) {
    if (caption2Descriptions.size() == 1 && caption2Descriptions.values().iterator().next().size() == 1) {
        OverrideDescription desc = caption2Descriptions.values().iterator().next().get(0);
        FileObject file = desc.location.getLocation().getFileObject();

        if (file != null) {
            UiUtils.open(file, desc.location.getLocation().getOffset());
        } else {
            Toolkit.getDefaultToolkit().beep();
        }

        return ;
    }
    
    Point position = new Point(p);

    SwingUtilities.convertPointToScreen(position, c);

    StringBuilder caption = new StringBuilder();
    List<OverrideDescription> descriptions = new LinkedList<OverrideDescription>();
    boolean first = true;

    for (Entry<String, List<OverrideDescription>> e : caption2Descriptions.entrySet()) {
        if (!first) {
            caption.append("/");
        }
        first = false;
        caption.append(e.getKey());
        descriptions.addAll(e.getValue());
    }

    PopupUtil.showPopup(new IsOverriddenPopup(caption.toString(), descriptions), caption.toString(), position.x, position.y, true, 0);
}
 
Example 28
Project: incubator-netbeans   File: URLMapper.java   Source Code and License 5 votes vote down vote up
public static URL findUrl(JTextComponent component) {
    synchronized (LOCK) {
        Collection<? extends URLMapper> mappers = getMappers();
        for(URLMapper m : mappers) {
            URL url = m.getUrl(component);
            if (url != null) {
                return url;
            }
        }
        return null;
    }
}
 
Example 29
Project: incubator-netbeans   File: SchemaBasedCompletionProvider.java   Source Code and License 5 votes vote down vote up
public CompletionTask createTask(int queryType, JTextComponent component) {
    if (queryType == COMPLETION_QUERY_TYPE || queryType == COMPLETION_ALL_QUERY_TYPE) {
        return new AsyncCompletionTask(new CompletionQuery(CompletionUtil.getPrimaryFile(component.getDocument())), component);
    }
    
    return null;
}
 
Example 30
Project: jdk8u-jdk   File: BasicBorders.java   Source Code and License 5 votes vote down vote up
public Insets getBorderInsets(Component c, Insets insets) {
    Insets margin = null;
    if (c instanceof JTextComponent) {
        margin = ((JTextComponent)c).getMargin();
    }
    insets.top = margin != null? 2+margin.top : 2;
    insets.left = margin != null? 2+margin.left : 2;
    insets.bottom = margin != null? 2+margin.bottom : 2;
    insets.right = margin != null? 2+margin.right : 2;

    return insets;
}
 
Example 31
Project: incubator-netbeans   File: Utilities.java   Source Code and License 5 votes vote down vote up
public static void setStatusText(JTextComponent c, String text) {
    EditorUI eui = getEditorUI(c);
    StatusBar sb = eui == null ? null : eui.getStatusBar();
    if (sb != null) {
        sb.setText(StatusBar.CELL_MAIN, text);
    }
}
 
Example 32
Project: incubator-netbeans   File: CompletionJListOperator.java   Source Code and License 5 votes vote down vote up
public static void start() {
    JTextComponent jtc = EditorRegistry.lastFocusedComponent();
    doc = jtc != null ? Utilities.getDocument(jtc) : null;
    if (doc != null) {
        doc.addDocumentListener(listener);
    }
    modified = false;
    active = true;
}
 
Example 33
Project: incubator-netbeans   File: MainMenuAction.java   Source Code and License 5 votes vote down vote up
protected @Override void setMenu(){
    super.setMenu();
    JTextComponent c = getComponent();
    MimePath mimePath = c == null ? MimePath.EMPTY : MimePath.parse(DocumentUtilities.getMimeType(c));
    Preferences prefs = MimeLookup.getLookup(mimePath).lookup(Preferences.class);
    boolean visible = prefs.getBoolean(SimpleValueNames.TOOLBAR_VISIBLE_PROP, EditorPreferencesDefaults.defaultToolbarVisible);
    SHOW_TOOLBAR_MENU.setState(visible);
}
 
Example 34
Project: incubator-netbeans   File: Utils.java   Source Code and License 5 votes vote down vote up
public static CodeProfilingPoint.Location getCurrentSelectionEndLocation(int lineOffset) {
    EditorContext mostActiveContext = EditorSupport.getMostActiveJavaEditorContext();

    if (mostActiveContext == null) {
        return CodeProfilingPoint.Location.EMPTY;
    }

    FileObject mostActiveJavaSource = mostActiveContext.getFileObject();

    if (mostActiveJavaSource == null) {
        return CodeProfilingPoint.Location.EMPTY;
    }

    JTextComponent mostActiveTextComponent = mostActiveContext.getTextComponent();

    if (mostActiveTextComponent.getSelectedText() == null) {
        return CodeProfilingPoint.Location.EMPTY;
    }

    String fileName = FileUtil.toFile(mostActiveJavaSource).getAbsolutePath();
    int lineNumber = EditorSupport.getLineForOffset(mostActiveJavaSource, mostActiveTextComponent.getSelectionEnd()) + 1;

    if (lineNumber == -1) {
        lineNumber = 1;
    }

    return new CodeProfilingPoint.Location(fileName, lineNumber,
                                           lineOffset /* TODO: get real line offset if lineOffset isn't OFFSET_START nor OFFSET_END */);
}
 
Example 35
Project: incubator-netbeans   File: BaseKit.java   Source Code and License 5 votes vote down vote up
public MultiKeymap getKeymap() {
    synchronized (KEYMAPS_AND_ACTIONS_LOCK) {
        MimePath mimePath = MimePath.parse(getContentType());
        MultiKeymap km = (MultiKeymap)kitKeymaps.get(mimePath);
        
        if (km == null) { // keymap not yet constructed
            // construct new keymap
            km = new MultiKeymap("Keymap for " + mimePath.getPath()); // NOI18N
            
            // retrieve key bindings for this kit and super kits
            KeyBindingSettings kbs = MimeLookup.getLookup(mimePath).lookup(KeyBindingSettings.class);
            List<org.netbeans.api.editor.settings.MultiKeyBinding> mkbList = kbs.getKeyBindings();
            List<JTextComponent.KeyBinding> editorMkbList = new  ArrayList<JTextComponent.KeyBinding>();
            
            for(org.netbeans.api.editor.settings.MultiKeyBinding mkb : mkbList) {
                List<KeyStroke> keyStrokes = mkb.getKeyStrokeList();
                MultiKeyBinding editorMkb = new MultiKeyBinding(keyStrokes.toArray(new KeyStroke[keyStrokes.size()]), mkb.getActionName());
                editorMkbList.add(editorMkb);
            }
            
            // go through all levels and collect key bindings
            km.load(editorMkbList.toArray(new JTextComponent.KeyBinding[editorMkbList.size()]), getActionMap());
            km.setDefaultAction(getActionMap().get(defaultKeyTypedAction));

            kitKeymaps.put(mimePath, km);
        }
        
        return km;
    }
}
 
Example 36
Project: incubator-netbeans   File: ExpandFoldTypeAction.java   Source Code and License 5 votes vote down vote up
public void actionPerformed (ActionEvent evt, JTextComponent target) {
    FoldHierarchy hierarchy = FoldHierarchy.get (target);
    // Hierarchy locking done in the utility method
    try {
        String mimeType = (java.lang.String) target.getDocument ().getProperty ("mimeType");
        Language l = LanguagesManager.getDefault ().getLanguage (mimeType);
        if (expand (hierarchy, l)) return;
        Iterator<Language> it = l.getImportedLanguages ().iterator ();
        while (it.hasNext ())
            if (expand (hierarchy, it.next ()))
                return;
    } catch (ParseException ex) {
    }
}
 
Example 37
Project: openjdk-jdk10   File: MultiTextUI.java   Source Code and License 5 votes vote down vote up
/**
 * Invokes the <code>getNextVisualPositionFrom</code> method on each UI handled by this object.
 *
 * @return the value obtained from the first UI, which is
 * the UI obtained from the default <code>LookAndFeel</code>
 */
public int getNextVisualPositionFrom(JTextComponent a, int b, Position.Bias c, int d, Position.Bias[] e)
        throws BadLocationException {
    int returnValue =
        ((TextUI) (uis.elementAt(0))).getNextVisualPositionFrom(a,b,c,d,e);
    for (int i = 1; i < uis.size(); i++) {
        ((TextUI) (uis.elementAt(i))).getNextVisualPositionFrom(a,b,c,d,e);
    }
    return returnValue;
}
 
Example 38
Project: incubator-netbeans   File: HighlightsViewUtils.java   Source Code and License 5 votes vote down vote up
private static Color validForeColor(AttributeSet attrs, JTextComponent textComponent) {
    Color foreColor = foreColor(attrs);
    if (foreColor == null) {
        foreColor = textComponent.getForeground();
    }
    if (foreColor == null) {
        foreColor = Color.BLACK;
    }
    return foreColor;
}
 
Example 39
Project: openjdk-jdk10   File: JTextComponentOperator.java   Source Code and License 5 votes vote down vote up
/**
 * Maps {@code JTextComponent.getCaret()} through queue
 */
public Caret getCaret() {
    return (runMapping(new MapAction<Caret>("getCaret") {
        @Override
        public Caret map() {
            return ((JTextComponent) getSource()).getCaret();
        }
    }));
}
 
Example 40
Project: gate-core   File: DocumentEditor.java   Source Code and License 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt) {
  if(searchDialog == null) {
    Window parent = SwingUtilities.getWindowAncestor(DocumentEditor.this);
    searchDialog =
        (parent instanceof Dialog)
            ? new SearchDialog((Dialog)parent)
            : new SearchDialog((Frame)parent);
    searchDialog.pack();
    searchDialog.setLocationRelativeTo(DocumentEditor.this);
    searchDialog.setResizable(true);
    MainFrame.getGuiRoots().add(searchDialog);
  }
  JTextComponent textPane = getTextComponent();
  // if the user never gives the focus to the textPane then
  // there will never be any selection in it so we force it
  textPane.requestFocusInWindow();
  // put the selection of the document into the search text field
  if(textPane.getSelectedText() != null) {
    searchDialog.patternTextField.setText(textPane.getSelectedText());
  }
  if(searchDialog.isVisible()) {
    searchDialog.toFront();
  } else {
    searchDialog.setVisible(true);
  }
  searchDialog.patternTextField.selectAll();
  searchDialog.patternTextField.requestFocusInWindow();
}
 
Example 41
Project: incubator-netbeans   File: ShowHierarchyAtCaretAction.java   Source Code and License 5 votes vote down vote up
private JavaSource getContext(JTextComponent target) {
    final Document doc = Utilities.getDocument(target);
    if (doc == null) {
        return null;
    }
    return JavaSource.forDocument(doc);
}
 
Example 42
Project: incubator-netbeans   File: CodeFoldingTestCase.java   Source Code and License 5 votes vote down vote up
private ValueResolver getResolver(final JTextComponent target){
    
    ValueResolver foldValueResolver = new ValueResolver(){
        public Object getValue(){
            FoldHierarchy hierarchy = FoldHierarchy.get(target);
            int dot = target.getCaret().getDot();
            hierarchy.lock();
            try{
                try{
                    int rowStart = javax.swing.text.Utilities.getRowStart(target, dot);
                    int rowEnd = javax.swing.text.Utilities.getRowEnd(target, dot);
                    Fold fold = getLineFold(hierarchy, dot, rowStart, rowEnd);
                    if (fold!=null){
                        return Boolean.valueOf(fold.isCollapsed());
                    }else{
                        return null;
                    }
                }catch(BadLocationException ble){
                    ble.printStackTrace();
                }
            }finally {
                hierarchy.unlock();
            }
            return null;
        }
    };
    
    return foldValueResolver;
}
 
Example 43
Project: incubator-netbeans   File: NbEditorUI.java   Source Code and License 5 votes vote down vote up
private synchronized Action getEditorAction(JTextComponent component) {
    if (editorAction == null) {
        BaseKit kit = Utilities.getKit(component);
        if (kit != null) {
            editorAction = kit.getActionByName(editorActionName);
        }
    }
    return editorAction;
}
 
Example 44
Project: incubator-netbeans   File: CPActionsImplementationProvider.java   Source Code and License 5 votes vote down vote up
public TextComponentTask(EditorCookie ec) {
    JTextComponent textC = ec.getOpenedPanes()[0];
    this.document = textC.getDocument();
    this.caretOffset = textC.getCaretPosition();
    this.selectionStart = textC.getSelectionStart();
    this.selectionEnd = textC.getSelectionEnd();
}
 
Example 45
Project: incubator-netbeans   File: HighlightsViewUtils.java   Source Code and License 5 votes vote down vote up
static double getMagicX(DocumentView docView, EditorView view, int offset, Bias bias, Shape alloc) {
    JTextComponent textComponent = docView.getTextComponent();
    if (textComponent == null) {
        return 0d;
    }
    Caret caret = textComponent.getCaret();
    Point magicCaretPoint = null;
    if(caret != null) {
        if(caret instanceof EditorCaret) {
            EditorCaret editorCaret = (EditorCaret) caret;
            CaretInfo info = editorCaret.getCaretAt(offset);
            magicCaretPoint = (info != null) ? info.getMagicCaretPosition() : null;
        } else {
            magicCaretPoint = caret.getMagicCaretPosition();
        }
    }
    double x;
    if (magicCaretPoint == null) {
        Shape offsetBounds = view.modelToViewChecked(offset, alloc, bias);
        if (offsetBounds == null) {
            x = 0d;
        } else {
            x = offsetBounds.getBounds2D().getX();
        }
    } else {
        x = magicCaretPoint.x;
    }
    return x;
}
 
Example 46
Project: incubator-netbeans   File: HtmlCompletionProvider.java   Source Code and License 5 votes vote down vote up
@Override
protected boolean canFilter(JTextComponent component) {
    try {
        if (component.getCaret() == null || component.getCaretPosition() < anchor) {
            return false;
        }
        
        Document doc = component.getDocument();
        int offset = component.getCaretPosition();

        String prefix = doc.getText(anchor, offset - anchor);

        //check the items
        for (CompletionItem item : items) {
            if (item instanceof HtmlCompletionItem) {
                String itemText = ((HtmlCompletionItem) item).getItemText();
                if(itemText != null) { //http://netbeans.org/bugzilla/show_bug.cgi?id=222234
                    if (startsWithIgnoreCase(itemText, prefix)) {
                        return true; //at least one item will remain
                    }
                } else {
                    LOG.log(Level.WARNING, "CompletionItem {0} returned null from getItemText()!", item);
                }
            }
        }


    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }

    return false;

}
 
Example 47
Project: incubator-netbeans   File: Editor.java   Source Code and License 5 votes vote down vote up
private boolean saveFile( Component comp ) {
    if( comp == null ) return false;
    JTextComponent edit = (JTextComponent)com2text.get( comp );
    Document doc = edit.getDocument();
    File file = (File)doc.getProperty( FILE );
    boolean created = ((Boolean)doc.getProperty( CREATED )).booleanValue();
    
    return saveFile( comp, file, created );
}
 
Example 48
Project: jdk8u-jdk   File: TransferHandler.java   Source Code and License 5 votes vote down vote up
private void setComponentDropLocation(TransferSupport support,
                                      boolean forDrop) {

    DropLocation dropLocation = (support == null)
                                ? null
                                : support.getDropLocation();

    if (SunToolkit.isInstanceOf(component, "javax.swing.text.JTextComponent")) {
        state = SwingAccessor.getJTextComponentAccessor().
                    setDropLocation((JTextComponent)component, dropLocation, state, forDrop);
    } else if (component instanceof JComponent) {
        state = ((JComponent)component).setDropLocation(dropLocation, state, forDrop);
    }
}
 
Example 49
Project: incubator-netbeans   File: BreadCrumbsTask.java   Source Code and License 5 votes vote down vote up
@Override
public void run(final ParserResult result, final SchedulerEvent event) {
    runWithCancelService(new Runnable() {
        @Override
        public void run() {
            resume();
            final long id = requestId.incrementAndGet();

            final Document doc = result.getSnapshot().getSource().getDocument(false);

            if (doc == null || !BreadcrumbsController.areBreadCrumsEnabled(doc)) return ;

            final int caret;

            if (event instanceof CursorMovedSchedulerEvent) {
                caret = ((CursorMovedSchedulerEvent) event).getCaretOffset();
            } else {
                //XXX: outside AWT!
                JTextComponent c = EditorRegistry.focusedComponent();

                if (c != null && c.getDocument() == doc)
                    caret = c.getCaretPosition();
                else
                    caret = (-1);
            }

            if (caret == (-1)) return ;

            final StructureItem structureRoot = computeStructureRoot(result.getSnapshot().getSource());

            if (structureRoot == null) return ;

            WORKER.post(new Runnable() {
                @Override public void run() {
                    selectNode(doc, structureRoot, id, caret);
                }
            });
        }
    });
}
 
Example 50
Project: jdk8u-jdk   File: AquaTextFieldSearch.java   Source Code and License 5 votes vote down vote up
static void updateCancelIcon(final JButton button, final JTextComponent text) {
    if (SwingUtilities.isEventDispatchThread()) {
        updateCancelIconOnEDT(button, text);
    } else {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() { updateCancelIconOnEDT(button, text); }
        });
    }
}
 
Example 51
Project: jdk8u-jdk   File: AquaTextFieldSearch.java   Source Code and License 5 votes vote down vote up
protected static void installSearchField(final JTextComponent c) {
    final SearchFieldBorder border = getSearchTextFieldBorder();
    c.setBorder(border);
    c.setLayout(border.getCustomLayout());
    c.add(getFindButton(c), BorderLayout.WEST);
    c.add(getCancelButton(c), BorderLayout.EAST);
    c.add(getPromptLabel(c), BorderLayout.CENTER);

    final TextUI ui = c.getUI();
    if (ui instanceof AquaTextFieldUI) {
        ((AquaTextFieldUI)ui).setPaintingDelegate(border);
    }
}
 
Example 52
Project: incubator-netbeans   File: BaseKit.java   Source Code and License 5 votes vote down vote up
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target != null) {
        Caret caret = target.getCaret();
        int dot = 0; // begin of document
        boolean select = selectionBeginAction.equals(getValue(Action.NAME));
        if (select) {
            caret.moveDot(dot);
        } else {
            caret.setDot(dot);
        }
    }
}
 
Example 53
Project: incubator-netbeans   File: EditorFindSupport.java   Source Code and License 5 votes vote down vote up
private void addCaretSelectText(JTextComponent c, int start, int end, boolean back) {
    Caret eCaret = c.getCaret();
    ensureVisible(c, start, end);
    if (eCaret instanceof EditorCaret) {
        EditorCaret caret = (EditorCaret) eCaret;
        try {
            caret.addCaret(c.getDocument().createPosition(end), Position.Bias.Forward,
                c.getDocument().createPosition(start), Position.Bias.Forward);
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
 
Example 54
Project: incubator-netbeans   File: ActionMappings.java   Source Code and License 5 votes vote down vote up
private static void replacePattern(String pattern, JTextComponent area, String replace, boolean select) {
    String props = area.getText();
    Matcher match = Pattern.compile(pattern, Pattern.DOTALL).matcher(props);
    if (match.matches()) {
        int begin = props.indexOf(TestChecker.PROP_SKIP_TEST);
        props = props.replace(TestChecker.PROP_SKIP_TEST + match.group(1), replace); //NOI18N
        area.setText(props);
        if (select) {
            area.setSelectionStart(begin);
            area.setSelectionEnd(begin + replace.length());
            area.requestFocusInWindow();
        }
    } else {
        String sep = "\n";//NOI18N
        if (props.endsWith("\n") || props.trim().length() == 0) {//NOI18N
            sep = "";//NOI18N
        }
        props = props + sep + replace; //NOI18N
        area.setText(props);
        if (select) {
            area.setSelectionStart(props.length() - replace.length());
            area.setSelectionEnd(props.length());
            area.requestFocusInWindow();
        }
    }

}
 
Example 55
Project: powertext   File: ParameterizedCompletionContext.java   Source Code and License 5 votes vote down vote up
/**
 * Activates parameter completion support.
 *
 * @see #deactivate()
 */
public void activate() {

	if (active) {
		return;
	}

	active = true;
	JTextComponent tc = ac.getTextComponent();
	lastSelectedParam = -1;

	if (pc.getShowParameterToolTip()) {
		tip = new ParameterizedCompletionDescriptionToolTip(
				parentWindow, this, ac, pc);
		try {
			int dot = tc.getCaretPosition();
			Rectangle r = tc.modelToView(dot);
			Point p = new Point(r.x, r.y);
			SwingUtilities.convertPointToScreen(p, tc);
			r.x = p.x;
			r.y = p.y;
			tip.setLocationRelativeTo(r);
			tip.setVisible(true);
		} catch (BadLocationException ble) { // Should never happen
			UIManager.getLookAndFeel().provideErrorFeedback(tc);
			ble.printStackTrace();
			tip = null;
		}
	}

	listener.install(tc);
	// First time through, we'll need to create this window.
	if (paramChoicesWindow==null) {
		paramChoicesWindow = createParamChoicesWindow();
	}
	lastSelectedParam = getCurrentParameterIndex();
	prepareParamChoicesWindow();
	paramChoicesWindow.setVisible(true);

}
 
Example 56
Project: incubator-netbeans   File: URLMapper.java   Source Code and License 5 votes vote down vote up
public static JTextComponent findTextComponenet(URL url) {
    synchronized (LOCK) {
        Collection<? extends URLMapper> mappers = getMappers();
        for(URLMapper m : mappers) {
            JTextComponent jtc = m.getTextComponent(url);
            if (jtc != null) {
                return jtc;
            }
        }
        return null;
    }
}
 
Example 57
Project: incubator-netbeans   File: MultiKeymap.java   Source Code and License 5 votes vote down vote up
/** Loads the key to action mappings into this keymap in similar way
* as JTextComponent.loadKeymap() does. This method is able to handle
* MultiKeyBindings but for compatibility it expects
* JTextComponent.KeyBinding array.
*/
public void load(JTextComponent.KeyBinding[] bindings, Action[] actions) {
    Map h = new HashMap(bindings.length);
    // add actions to map to resolve by names quickly
    for (int i = 0; i < actions.length; i++) {
        Action a = actions[i];
        String value = (String)a.getValue(Action.NAME);
        h.put((value != null ? value : ""), a); // NOI18N
    }
    load(bindings, h);
}
 
Example 58
Project: Equella   File: I18nTextField.java   Source Code and License 5 votes vote down vote up
public PopupPanel(JPopupMenu popup)
{
	this.popup = popup;
	this.mapping = new HashMap<Locale, JTextComponent>();

	setLayout(new MigLayout("wrap,fill", "[grow]r[]", "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
	for( Locale locale : editableLocales )
	{
		String actionCommand = locale.toString();
		JTextComponent field = getTextComponent();

		JButton button = new JButton(locale.getDisplayName());
		button.setActionCommand(actionCommand);
		button.addActionListener(this);

		field.setText(textMap.get(locale));
		mapping.put(locale, field);

		add(prepareTextComponent(field), "growx, sizegroup f, hmax 100px"); //$NON-NLS-1$
		add(button, "sizegroup b"); //$NON-NLS-1$
	}

	closeButton = new JLinkButton(CurrentLocale.get("prompts.close")); //$NON-NLS-1$
	closeButton.addActionListener(this);
	closeButton.setActionCommand(""); //$NON-NLS-1$
	closeButton.setIcon(new ArrowIcon(SwingConstants.NORTH));
	closeButton.setHorizontalTextPosition(SwingConstants.LEFT);
	add(closeButton, "span 2, align right, shrink"); //$NON-NLS-1$

	setBorder(BorderFactory.createLineBorder(Color.BLACK));

	final int width = Math.max(400, I18nTextField.this.getSize().width);
	setPreferredSize(new Dimension(width, getPreferredSize().height));

	popup.addPopupMenuListener(this);
}
 
Example 59
Project: HBaseClient   File: TruncateActionListener.java   Source Code and License 4 votes vote down vote up
@Override
public void onClick(ActionEvent arg0)
{
    String v_TableName = this.getAppFrame().getTableName();
    
    if ( JavaHelp.isNull(v_TableName) )
    {
        this.getAppFrame().showHintInfo("请先选择要清空的表" ,Color.BLUE);
        return;
    }
    
    int v_Ret = JOptionPane.showConfirmDialog(this.getAppFrame() ,"确认要清空表的所有记录?清空后数据将无法恢复。" ,"确认对话框" , JOptionPane.YES_NO_OPTION);
    
    if ( v_Ret == JOptionPane.YES_OPTION )
    {
        // Nothing.
    }
    else
    {
        this.getAppFrame().showHintInfo("您取消了清空表操作" ,Color.BLUE);
        return;
    }
    
    
    try
    {
        this.getHBase().truncate(v_TableName);
        
        ((JTextComponent)XJava.getObject("RowKey"))     .setText("");
        ((JTextComponent)XJava.getObject("ColumnValue")).setText("");
        ((JCheckBox)     XJava.getObject("IsLike"))     .setSelected(true);
        ((JComboBox)     XJava.getObject("FamilyName")) .setSelectedIndex(0);
        ((JComboBox)     XJava.getObject("ColumnName")) .setSelectedIndex(0);
        
        ((JButton)XJava.getObject("xbSubmit")).doClick();
    }
    catch (Exception exce)
    {
        this.getAppFrame().showHintInfo("清空表异常:" + exce.getMessage() ,Color.RED);
    }
}
 
Example 60
Project: incubator-netbeans   File: CodeTemplateCompletionItem.java   Source Code and License 4 votes vote down vote up
public boolean instantSubstitution(JTextComponent component) {
    // defaultAction(component);
    return false;
}