Java Code Examples for javax.swing.text.JTextComponent#getSelectedText()

The following examples show how to use javax.swing.text.JTextComponent#getSelectedText() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConvertToCCAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
   protected boolean enable(Node[] activatedNodes) {
//enables the action only if the first activated node
//contains DataObject instance which is currently associated
//with edited document
if (activatedNodes.length > 0) {
    Node node = activatedNodes[0]; //multiselection doesn't make sense
    DataObject dobj = node.getLookup().lookup(DataObject.class);
    if (dobj != null) {
	JTextComponent tc = EditorRegistry.lastFocusedComponent();
	if (tc != null && tc.getSelectedText() != null) { //disable w/o editor selection
	    DataObject editedDobj = NbEditorUtilities.getDataObject(tc.getDocument());
	    if (editedDobj != null && editedDobj.equals(dobj)) {
		return true;
	    }
	}
    }
}
return false;
   }
 
Example 2
Source File: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Get the selection if there's any or get the identifier around
   * the position if there's no selection.
   */
   public static String getSelectionOrIdentifier(JTextComponent c, int offset)
   throws BadLocationException {
       Document doc = c.getDocument();
       Caret caret = c.getCaret();
       String ret;
       if (Utilities.isSelectionShowing(caret)) {
           ret = c.getSelectedText();
    if (ret != null) return ret;
       } 
if (doc instanceof BaseDocument){
    ret = getIdentifier((BaseDocument) doc, offset);
       } else {
    ret = getWord(c, offset);
}
       return ret;
   }
 
Example 3
Source File: ActionUtils.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Expand the string template and replaces the selection with the expansion
 * of the template.  The template String may contain any of the following
 * special tags.
 *
 * <li>{@code #{selection}} replaced with the selection, if any.  If there is
 * no selection, then the {@code #{selection}} tag will be removed.
 * <li>{@code #{p:AnyText}} will be replaced by {@code any text} and then
 * set the text selection to {@code AnyText}
 *
 * This methood does NOT perform any indentation and the template should
 * generally span one line only
 *
 * @param target
 * @param template
 */
public static void insertSimpleTemplate(JTextComponent target, String template) {
	String selected = target.getSelectedText();
	selected = (selected == null) ? "" : selected;
	StringBuffer sb = new StringBuffer(template.length());
	Matcher pm = PTAGS_PATTERN.matcher(template.replace(TEMPLATE_SELECTION, selected));
	int selStart = -1, selEnd = -1;
	int lineStart = 0;
	while (pm.find()) {
		selStart = pm.start() + lineStart;
		pm.appendReplacement(sb, pm.group(1));
		selEnd = sb.length();
	}
	pm.appendTail(sb);
	// String expanded = template.replace(TEMPLATE_SELECTION, selected);

	if (selStart >= 0) {
		selStart += target.getSelectionStart();
		selEnd += target.getSelectionStart();
	}
	target.replaceSelection(sb.toString());
	if (selStart >= 0) {
		// target.setCaretPosition(selStart);
		target.select(selStart, selEnd);
	}
}
 
Example 4
Source File: PopupEncoderMenu.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isEnableForComponent(Component invoker) {
    if (invoker instanceof JTextComponent && !isInvokerFromEncodeDecode(invoker)) {

        JTextComponent txt = (JTextComponent) invoker;
        String sel = txt.getSelectedText();
        if (sel == null || sel.length() == 0) {
            this.setEnabled(false);
        } else {
            this.setEnabled(true);
        }

        setLastInvoker((JTextComponent) invoker);
        return true;
    }

    setLastInvoker(null);
    return false;
}
 
Example 5
Source File: DocumentEditor.java    From gate-core with GNU Lesser General Public License v3.0 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 6
Source File: NetAdmin.java    From nullpomino with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void show(Component c, int x, int y) {
	JTextComponent field = (JTextComponent) c;
	boolean flg = field.getSelectedText() != null;
	cutAction.setEnabled(flg);
	copyAction.setEnabled(flg);
	deleteAction.setEnabled(flg);
	selectAllAction.setEnabled(field.isFocusOwner());
	super.show(c, x, y);
}
 
Example 7
Source File: CopyHandler.java    From jeveassets with GNU General Public License v2.0 5 votes vote down vote up
public static void cut(JTextComponent jText) {
	String s = jText.getSelectedText();
	if (s == null) {
		return;
	}
	if (s.length() == 0) {
		return;
	}
	String text = jText.getText();
	String before = text.substring(0, jText.getSelectionStart());
	String after = text.substring(jText.getSelectionEnd(), text.length());
	jText.setText(before + after);
	CopyHandler.toClipboard(s);
}
 
Example 8
Source File: TextComponentPopupMenu.java    From finalspeed-91yun with GNU General Public License v2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent e) {
	JTextComponent tc = (JTextComponent) getInvoker();

	String sel = tc.getSelectedText();

	if (e.getSource() == cutItem) {
		tc.cut();
	} else if (e.getSource() == copyItem) {
		tc.copy();
	} else if (e.getSource() == pasteItem) {
		tc.paste();
	} else if (e.getSource() == selectAllItem) {
		tc.selectAll();
	} else if (e.getSource() == deleteItem) {
		Document doc = tc.getDocument();
		int start = tc.getSelectionStart();
		int end = tc.getSelectionEnd();

		try {
			Position p0 = doc.createPosition(start);
			Position p1 = doc.createPosition(end);

			if ((p0 != null) && (p1 != null)
					&& (p0.getOffset() != p1.getOffset())) {
				doc.remove(p0.getOffset(), p1.getOffset() - p0.getOffset());
			}
		} catch (BadLocationException be) {
		}
	}
}
 
Example 9
Source File: TextComponentPopupMenu.java    From finalspeed-91yun with GNU General Public License v2.0 5 votes vote down vote up
public void show(Component invoker, int x, int y) {
	JTextComponent tc = (JTextComponent) invoker;
	String sel = tc.getSelectedText();

	boolean selected = sel != null && !sel.equals("");
	boolean enableAndEditable = tc.isEnabled() && tc.isEditable();

	cutItem.setEnabled(selected && enableAndEditable);
	copyItem.setEnabled(selected && tc.isEnabled());
	deleteItem.setEnabled(selected && enableAndEditable);
	pasteItem.setEnabled(enableAndEditable);
	selectAllItem.setEnabled(tc.isEnabled());

	super.show(invoker, x, y);
}
 
Example 10
Source File: SyntaxEditorKit.java    From nextreports-designer with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent event) {
    JTextComponent target = getTextComponent(event);
    if (target != null) {
        String selected = target.getSelectedText();
        if (selected == null) {
            PlainDocument pDoc = (PlainDocument) target.getDocument();
            Integer tabStop = (Integer) pDoc.getProperty(PlainDocument.tabSizeAttribute);
            // insert needed number of tabs:
            int lineStart = pDoc.getParagraphElement(target.getCaretPosition()).getStartOffset();
            // column 
            int column = target.getCaretPosition() - lineStart;
            int needed = tabStop - (column % tabStop);
            target.replaceSelection(SyntaxUtil.SPACES.substring(0, needed));
        } else {
            String[] lines = SyntaxUtil.getSelectedLines(target);
            int start = target.getSelectionStart();
            StringBuilder sb = new StringBuilder();
            for (String line : lines) {
                sb.append('\t');
                sb.append(line);
                sb.append('\n');
            }
            target.replaceSelection(sb.toString());
            target.select(start, start + sb.length());
        }
    }
}
 
Example 11
Source File: IPV4Field.java    From lippen-network-tool with Apache License 2.0 5 votes vote down vote up
public void keyPressed(KeyEvent e) {
    JTextComponent field = (JTextComponent) e.getComponent();
    int keyCode = e.getKeyCode();
    char keyChar = e.getKeyChar();
    String text = field.getText();
    String selText = field.getSelectedText();
    int caretPos = field.getCaretPosition();
    int textLength = text.length();
    if ((keyCode == KeyEvent.VK_LEFT) && (caretPos == 0)
            && (selText == null)) {
        field.firePropertyChange("Left", 0, 1);
    } else if (((keyCode == KeyEvent.VK_RIGHT)
            && (caretPos == textLength) && (selText == null))
            || ((keyChar == '.') && (!text.isEmpty()) && (selText == null))) {
        field.firePropertyChange("Right", 0, 1);
    } else if ((keyCode == KeyEvent.VK_BACK_SPACE) && (caretPos == 0)
            && (selText == null)) {
        field.firePropertyChange("BackSpace", 0, 1);
    } else if ((keyCode == KeyEvent.VK_DELETE)
            && (caretPos == textLength) && (selText == null)) {
        field.firePropertyChange("Delete", 0, 1);
    } else if (keyCode == KeyEvent.VK_HOME) {
        IPV4Field.this.ipFields[0].unSelectAllWhenFocusGained();
        IPV4Field.this.ipFields[0].requestFocus();
        IPV4Field.this.ipFields[0].setCaretPosition(0);
    } else if (keyCode == KeyEvent.VK_END) {
        int last = IPV4Field.this.ipFields.length - 1;
        textLength = IPV4Field.this.ipFields[last].getText()
                .length();
        IPV4Field.this.ipFields[last]
                .unSelectAllWhenFocusGained();
        IPV4Field.this.ipFields[last].requestFocus();
        IPV4Field.this.ipFields[last]
                .setCaretPosition(textLength);
    } else if ((keyCode == KeyEvent.VK_0 || keyCode == KeyEvent.VK_NUMPAD0) && (caretPos == 0 || (text != null && text.equals(selText)))) {
        field.firePropertyChange("Right", 0, 1);
    } else if (("0123456789".indexOf(keyChar) >= 0)) {
        if (selText == null) {
            int ipInt = (text.length() == 0 ? 0 : Integer
                    .parseInt(text));

            if (ipInt > 25) {
                field.firePropertyChange("Right", 0, 1);
            }
        } else {
            if (field.getSelectionStart() == 2
                    && field.getSelectionEnd() == 3) {
                field.firePropertyChange("Right", 0, 1);
            }
        }
    }
}
 
Example 12
Source File: TextComponentPopupMenu.java    From finalspeed with GNU General Public License v2.0 5 votes vote down vote up
public void show(Component invoker, int x, int y) {
    JTextComponent tc = (JTextComponent) invoker;
    String sel = tc.getSelectedText();

    boolean selected = sel != null && !sel.equals("");
    boolean enableAndEditable = tc.isEnabled() && tc.isEditable();

    cutItem.setEnabled(selected && enableAndEditable);
    copyItem.setEnabled(selected && tc.isEnabled());
    deleteItem.setEnabled(selected && enableAndEditable);
    pasteItem.setEnabled(enableAndEditable);
    selectAllItem.setEnabled(tc.isEnabled());

    super.show(invoker, x, y);
}
 
Example 13
Source File: NetAdmin.java    From nullpomino with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void show(Component c, int x, int y) {
	JTextComponent field = (JTextComponent) c;
	boolean flg = field.getSelectedText() != null;
	copyAction.setEnabled(flg);
	selectAllAction.setEnabled(field.isFocusOwner());
	super.show(c, x, y);
}
 
Example 14
Source File: AddCaretSelectNextAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target != null) {
        Caret caret = target.getCaret();
        if (Utilities.isSelectionShowing(caret)) {
            EditorFindSupport findSupport = EditorFindSupport.getInstance();
            HashMap<String, Object> props = new HashMap<>(findSupport.createDefaultFindProperties());
            String searchWord = target.getSelectedText();
            int n = searchWord.indexOf('\n');
            if (n >= 0) {
                searchWord = searchWord.substring(0, n);
            }
            props.put(EditorFindSupport.FIND_WHAT, searchWord);
            props.put(EditorFindSupport.ADD_MULTICARET, Boolean.TRUE);
            EditorUI eui = org.netbeans.editor.Utilities.getEditorUI(target);
            if (eui.getComponent().getClientProperty("AsTextField") == null) { //NOI18N
                findSupport.setFocusedTextComponent(eui.getComponent());
            }
            findSupport.putFindProperties(props);
            findSupport.find(null, false);
            props.put(EditorFindSupport.ADD_MULTICARET, Boolean.FALSE);
            findSupport.putFindProperties(props);
        } else {
            try {
                int[] identifierBlock = Utilities.getIdentifierBlock((BaseDocument) target.getDocument(), caret.getDot());
                if (identifierBlock != null) {
                    caret.setDot(identifierBlock[0]);
                    caret.moveDot(identifierBlock[1]);
                }
            } catch (BadLocationException e) {
                LOGGER.log(Level.WARNING, null, e);
            }
        }
    }
}
 
Example 15
Source File: TextComponentPopupMenu.java    From xtunnel with GNU General Public License v2.0 5 votes vote down vote up
public void show(Component invoker, int x, int y) {
	JTextComponent tc = (JTextComponent) invoker;
	String sel = tc.getSelectedText();

	boolean selected = sel != null && !sel.equals("");
	boolean enableAndEditable = tc.isEnabled() && tc.isEditable();

	cutItem.setEnabled(selected && enableAndEditable);
	copyItem.setEnabled(selected && tc.isEnabled());
	deleteItem.setEnabled(selected && enableAndEditable);
	pasteItem.setEnabled(enableAndEditable);
	selectAllItem.setEnabled(tc.isEnabled());

	super.show(invoker, x, y);
}
 
Example 16
Source File: Utils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static CodeProfilingPoint.Location getCurrentSelectionStartLocation(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.getSelectionStart()) + 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 17
Source File: TextComponentPopupMenu.java    From xtunnel with GNU General Public License v2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent e) {
	JTextComponent tc = (JTextComponent) getInvoker();
	@SuppressWarnings("unused")
	String sel = tc.getSelectedText();

	if (e.getSource() == cutItem) {
		tc.cut();
	} else if (e.getSource() == copyItem) {
		tc.copy();
	} else if (e.getSource() == pasteItem) {
		tc.paste();
	} else if (e.getSource() == selectAllItem) {
		tc.selectAll();
	} else if (e.getSource() == deleteItem) {
		Document doc = tc.getDocument();
		int start = tc.getSelectionStart();
		int end = tc.getSelectionEnd();

		try {
			Position p0 = doc.createPosition(start);
			Position p1 = doc.createPosition(end);

			if ((p0 != null) && (p1 != null)
					&& (p0.getOffset() != p1.getOffset())) {
				doc.remove(p0.getOffset(), p1.getOffset() - p0.getOffset());
			}
		} catch (BadLocationException be) {
		}
	}
}
 
Example 18
Source File: Utils.java    From netbeans with Apache License 2.0 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 19
Source File: FindTextAction.java    From wpcleaner with Apache License 2.0 4 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
  JTextComponent text = (textPane != null) ? textPane : getTextComponent(e);
  String currentSearch = search;
  if ((currentSearch == null) || (currentSearch.isEmpty())) {
    currentSearch = text.getSelectedText();
  }
  if ((currentSearch == null) || (currentSearch.isEmpty())) {
    currentSearch = lastSearch;
  }
  currentSearch = JOptionPane.showInputDialog(
      text.getParent(),
      GT._T("String to find"),
      currentSearch);
  if ((currentSearch == null) || ("".equals(currentSearch.trim()))) {
    return;
  }
  lastSearch = currentSearch;
  String textPattern = "";
  char firstChar = lastSearch.charAt(0);
  if (Character.isLetter(firstChar)) {
    textPattern =
        "[" + Character.toUpperCase(firstChar) + Character.toLowerCase(firstChar) + "]" +
        Pattern.quote(lastSearch.substring(1));
  } else {
    textPattern = Pattern.quote(lastSearch);
  }
  Pattern pattern = Pattern.compile(textPattern);
  Matcher matcher = pattern.matcher(text.getText());
  if (matcher.find(text.getCaretPosition())) {
    text.setCaretPosition(matcher.start());
    text.moveCaretPosition(matcher.end());
    text.requestFocus();
    return;
  }
  if (matcher.find(0)) {
    text.setCaretPosition(matcher.start());
    text.moveCaretPosition(matcher.end());
    text.requestFocus();
    return;
  }
}
 
Example 20
Source File: AddCaretSelectAllAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target != null) {
        Caret caret = target.getCaret();
        if (!Utilities.isSelectionShowing(caret)) {
            try {
                int[] identifierBlock = Utilities.getIdentifierBlock((BaseDocument) target.getDocument(), caret.getDot());
                if (identifierBlock != null) {
                    caret.setDot(identifierBlock[0]);
                    caret.moveDot(identifierBlock[1]);
                }
            } catch (BadLocationException e) {
                LOGGER.log(Level.WARNING, null, e);
            }
        }

        EditorFindSupport findSupport = EditorFindSupport.getInstance();
        HashMap<String, Object> props = new HashMap<>(findSupport.createDefaultFindProperties());
        String searchWord = target.getSelectedText();
        if (searchWord != null) {
            int n = searchWord.indexOf('\n');
            if (n >= 0) {
                searchWord = searchWord.substring(0, n);
            }
            props.put(EditorFindSupport.FIND_WHAT, searchWord);
            Document doc = target.getDocument();
            EditorUI eui = org.netbeans.editor.Utilities.getEditorUI(target);
            if (eui.getComponent().getClientProperty("AsTextField") == null) { //NOI18N
                findSupport.setFocusedTextComponent(eui.getComponent());
            }
            findSupport.putFindProperties(props);
            findSupport.find(null, false);

            if (caret instanceof EditorCaret) {
                EditorCaret editorCaret = (EditorCaret) caret;
                try {
                    int[] blocks = findSupport.getBlocks(new int[]{-1, -1}, doc, 0, doc.getLength());
                    if (blocks[0] >= 0 && blocks.length % 2 == 0) {
                        List<Position> newCarets = new ArrayList<>();

                        for (int i = 0; i < blocks.length; i += 2) {
                            int start = blocks[i];
                            int end = blocks[i + 1];
                            if (start == -1 || end == -1) {
                                break;
                            }
                            Position startPos = doc.createPosition(start);
                            Position endPos = doc.createPosition(end);
                            newCarets.add(endPos);
                            newCarets.add(startPos);
                        }

                        editorCaret.replaceCarets(newCarets, null); // TODO handle biases
                    }
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
    }
}