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   View source code 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   View source code 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: incubator-netbeans   File: Editor.java   View source code 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 4
Project: incubator-netbeans   File: ComponentUtils.java   View source code 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 5
Project: incubator-netbeans   File: JavadocCompletionItem.java   View source code 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 6
Project: incubator-netbeans   File: GlyphGutter.java   View source code 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 7
Project: incubator-netbeans   File: MasterMatcher.java   View source code 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 8
Project: incubator-netbeans   File: GsfCompletionItem.java   View source code 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 9
Project: OpenJSharp   File: CAccessibleText.java   View source code 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 10
Project: incubator-netbeans   File: AnnotationViewDataImpl.java   View source code 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 11
Project: openjdk-jdk10   File: TextComponentPrintable.java   View source code 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 12
Project: incubator-netbeans   File: RevertModifications.java   View source code 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 13
Project: incubator-netbeans   File: OverrideEditorActions.java   View source code 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 14
Project: incubator-netbeans   File: FoldHierarchyTransactionImpl.java   View source code 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 15
Project: incubator-netbeans   File: GoToSuperTypeAction.java   View source code 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 16
Project: incubator-netbeans   File: EndTagResultItem.java   View source code 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 17
Project: incubator-netbeans   File: CamelCaseOperations.java   View source code 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 18
Project: incubator-netbeans   File: Registry.java   View source code 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 19
Project: incubator-netbeans   File: AnnotationBar.java   View source code 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 20
Project: incubator-netbeans   File: Utilities.java   View source code 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 21
Project: incubator-netbeans   File: InsertSemicolonAction.java   View source code 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 22
Project: openjdk-jdk10   File: AquaTextFieldSearch.java   View source code 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 23
Project: incubator-netbeans   File: AnnotationViewDataImpl.java   View source code 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 24
Project: incubator-netbeans   File: WordCompletion.java   View source code 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 25
Project: powertext   File: ParameterizedCompletionContext.java   View source code 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 26
Project: incubator-netbeans   File: IsOverriddenAnnotationAction.java   View source code 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 27
Project: incubator-netbeans   File: URLMapper.java   View source code 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 28
Project: incubator-netbeans   File: SchemaBasedCompletionProvider.java   View source code 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 29
Project: jdk8u-jdk   File: BasicBorders.java   View source code 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 30
Project: incubator-netbeans   File: Utilities.java   View source code 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 31
Project: incubator-netbeans   File: CompletionJListOperator.java   View source code 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 32
Project: incubator-netbeans   File: MainMenuAction.java   View source code 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 33
Project: incubator-netbeans   File: Utils.java   View source code 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 34
Project: incubator-netbeans   File: BaseKit.java   View source code 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 35
Project: enigma-vk   File: BoxHighlightPainter.java   View source code 5 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 36
Project: incubator-netbeans   File: ExpandFoldTypeAction.java   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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();
}