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

The following examples show how to use javax.swing.text.JTextComponent#getText() . 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: GTableToCSV.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private static String lookForTextInsideOfComponent(Component component) {
	if (!(component instanceof Container)) {
		return null;
	}
	Container container = (Container) component;
	Component[] components = container.getComponents();
	for (Component child : components) {
		if (child instanceof JLabel) {
			// check for a label with text (one without text could be used for an icon)
			JLabel label = (JLabel) child;
			String text = label.getText();
			if (text != null) {
				return text;
			}
		}
		else if (child instanceof JTextComponent) {
			// surely this is for displaying text
			JTextComponent textComponent = (JTextComponent) child;
			return textComponent.getText();
		}
	}

	return null;
}
 
Example 2
Source File: SQLEntryPanelUtil.java    From bigtable-sql with Apache License 2.0 6 votes vote down vote up
public static int[] getWordBoundsAtCursor(JTextComponent textComponent, boolean qualified)
{
   String text = textComponent.getText();
   int caretPos = textComponent.getCaretPosition();

   int[] beginAndEndPos = new int[2];

   int lastIndexOfText = Math.max(0,text.length()-1);
   beginAndEndPos[0] = Math.min(caretPos, lastIndexOfText); // The Math.min is for the Caret at the end of the text
   while(0 < beginAndEndPos[0])
   {
      if(isParseStop(text.charAt(beginAndEndPos[0] - 1), false == qualified))
      {
         break;
      }
      --beginAndEndPos[0];
   }

   beginAndEndPos[1] = caretPos;
   while(beginAndEndPos[1] < text.length() && false == isParseStop(text.charAt(beginAndEndPos[1]), true))
   {
      ++beginAndEndPos[1];
   }
   return beginAndEndPos;
}
 
Example 3
Source File: ReturnTypeUIHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Object getItem() {
    
    JTextComponent editor = getEditor();
    
    Object newValue = editor.getText();

    if (oldValue != null && !(oldValue instanceof String))  {
        // The original value is not a string. Should return the value in it's
        // original type.
        if (newValue.equals(oldValue.toString()))  {
            return oldValue;
        } else {
            // Must take the value from the editor and get the value and cast it to the new type.
            Class<?> cls = oldValue.getClass();
            try {
                Method method = cls.getMethod("valueOf", String.class); // NOI18N
                newValue = method.invoke(oldValue, new Object[] { editor.getText() });
            } catch (Exception ex) {
                // Fail silently and return the newValue (a String object)
                Logger.getLogger("ReturnTypeUIHelper").log(Level.FINE, "ignored excep[tion", ex);  //NOI18N
            }
        }
    }
    return newValue;
}
 
Example 4
Source File: NameAutocompleter.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private boolean isExpectedNext(JTextComponent input, String nextChar)
{
	String expected;
	if (input.getSelectionStart() < input.getSelectionEnd())
	{
		try
		{
			expected = input.getText(input.getSelectionStart(), 1);
		}
		catch (BadLocationException ex)
		{
			log.warn("Could not get first character from input selection.", ex);
			return false;
		}
	}
	else
	{
		expected = "";
	}
	return nextChar.equalsIgnoreCase(expected);
}
 
Example 5
Source File: SearchReplaceComponent.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void addTextToRecent(@Nonnull JTextComponent textField) {
  final String text = textField.getText();
  if (text.length() > 0) {
    FindInProjectSettings findInProjectSettings = FindInProjectSettings.getInstance(myProject);
    if (textField == mySearchTextComponent) {
      findInProjectSettings.addStringToFind(text);
      if (mySearchFieldWrapper.getTargetComponent() instanceof SearchTextField) {
        ((SearchTextField)mySearchFieldWrapper.getTargetComponent()).addCurrentTextToHistory();
      }
    }
    else {
      findInProjectSettings.addStringToReplace(text);
      if (myReplaceFieldWrapper.getTargetComponent() instanceof SearchTextField) {
        ((SearchTextField)myReplaceFieldWrapper.getTargetComponent()).addCurrentTextToHistory();
      }
    }
  }
}
 
Example 6
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 7
Source File: CopyHandler.java    From jeveassets with GNU General Public License v2.0 5 votes vote down vote up
public static void paste(JTextComponent jText) {
	String s = CopyHandler.fromClipboard();
	if (s == null) {
		return;
	}
	String text = jText.getText();
	String before = text.substring(0, jText.getSelectionStart());
	String after = text.substring(jText.getSelectionEnd(), text.length());
	jText.setText(before + s + after);
	int caretPosition = before.length() + s.length();
	if (caretPosition <= jText.getText().length()) {
		jText.setCaretPosition(before.length() + s.length());
	}
}
 
Example 8
Source File: ContextMenuMouseListener.java    From ripme with MIT License 5 votes vote down vote up
@Override
public void mouseClicked(MouseEvent e) {
    if (e.getModifiers() == InputEvent.BUTTON3_MASK) {
        if (!(e.getSource() instanceof JTextComponent)) {
            return;
        }

        textComponent = (JTextComponent) e.getSource();
        textComponent.requestFocus();

        boolean enabled = textComponent.isEnabled();
        boolean editable = textComponent.isEditable();
        boolean nonempty = !(textComponent.getText() == null || textComponent.getText().equals(""));
        boolean marked = textComponent.getSelectedText() != null;

        boolean pasteAvailable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null).isDataFlavorSupported(DataFlavor.stringFlavor);

        undoAction.setEnabled(enabled && editable && (lastActionSelected == Actions.CUT || lastActionSelected == Actions.PASTE));
        cutAction.setEnabled(enabled && editable && marked);
        copyAction.setEnabled(enabled && marked);
        pasteAction.setEnabled(enabled && editable && pasteAvailable);
        selectAllAction.setEnabled(enabled && nonempty);

        int nx = e.getX();

        if (nx > 500) {
            nx = nx - popup.getSize().width;
        }

        popup.show(e.getComponent(), nx, e.getY() - popup.getSize().height);
    }
}
 
Example 9
Source File: ActionMappings.java    From netbeans with Apache License 2.0 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 10
Source File: ComboInplaceEditor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void prepareEditor() {
    Component c = getEditor().getEditorComponent();

    if (c instanceof JTextComponent) {
        JTextComponent jtc = (JTextComponent) c;
        String s = jtc.getText();

        if ((s != null) && (s.length() > 0)) {
            jtc.setSelectionStart(0);
            jtc.setSelectionEnd(s.length());
        }

        if (tableUI) {
            jtc.setBackground(getBackground());
        } else {
            jtc.setBackground(PropUtils.getTextFieldBackground());
        }
        if( tableUI )
            jtc.requestFocus();
    }

    if (getLayout() != null) {
        getLayout().layoutContainer(this);
    }

    repaint();
}
 
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: ClipboardActionsPopup.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
private int getTextLength(JTextComponent c) {
	if (c == null) {
		return 0;
	}
	if (c.getText() == null) {
		return 0;
	}
	return c.getText().length();
}
 
Example 13
Source File: NameAutocompleter.java    From runelite with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void keyTyped(KeyEvent e)
{
	if (!hiscoreConfig.autocomplete())
	{
		return;
	}

	final JTextComponent input = (JTextComponent)e.getSource();
	final String inputText = input.getText();

	// Only autocomplete if the selection end is at the end of the text.
	if (input.getSelectionEnd() != inputText.length())
	{
		return;
	}

	// Character to be inserted at the selection start.
	final String charToInsert = Character.toString(e.getKeyChar());

	// Don't attempt to autocomplete if the name is invalid.
	// This condition is also true when the user presses a key like backspace.
	if (INVALID_CHARS.matcher(charToInsert).find()
		|| INVALID_CHARS.matcher(inputText).find())
	{
		return;
	}

	// Check if we are already autocompleting.
	if (autocompleteName != null && autocompleteNamePattern.matcher(inputText).matches())
	{
		if (isExpectedNext(input, charToInsert))
		{
			try
			{
				// Insert the character and move the selection.
				final int insertIndex = input.getSelectionStart();
				Document doc = input.getDocument();
				doc.remove(insertIndex, 1);
				doc.insertString(insertIndex, charToInsert, null);
				input.select(insertIndex + 1, input.getSelectionEnd());
			}
			catch (BadLocationException ex)
			{
				log.warn("Could not insert character.", ex);
			}

			// Prevent default behavior.
			e.consume();
		}
		else // Character to insert does not match current autocompletion. Look for another name.
		{
			newAutocomplete(e);
		}
	}
	else // Search for a name to autocomplete
	{
		newAutocomplete(e);
	}
}
 
Example 14
Source File: SwingUtil.java    From jts with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static String value(JTextComponent txt) {
  return txt.getText();
}
 
Example 15
Source File: EditableHistoryCombo.java    From visualvm with GNU General Public License v2.0 4 votes vote down vote up
public String getText() {
    JTextComponent textC = getTextComponent();
    return textC != null ? textC.getText() : getSelectedItem().toString();
}
 
Example 16
Source File: EditableHistoryCombo.java    From visualvm with GNU General Public License v2.0 4 votes vote down vote up
public String getText() {
    JTextComponent textC = getTextComponent();
    return textC != null ? textC.getText() : getSelectedItem().toString();
}
 
Example 17
Source File: EditableHistoryCombo.java    From netbeans with Apache License 2.0 4 votes vote down vote up
String getText() {
    JTextComponent textC = getTextComponent();
    return textC != null ? textC.getText() : getSelectedItem().toString();
}
 
Example 18
Source File: ImageFileAssistantPage2.java    From snap-desktop with GNU General Public License v3.0 4 votes vote down vote up
private String getText(JTextComponent textComponent) {
    String s = textComponent.getText();
    return s != null ? s.trim() : "";
}
 
Example 19
Source File: AnimationCompletionProvider.java    From 3Dscript with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected List<Completion> getCompletionsImpl(JTextComponent comp) {
	String text = comp.getText();
	int dot = comp.getCaretPosition();
	return getCompletionsImpl(text, dot);
}
 
Example 20
Source File: TextComponentState.java    From weblaf with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Constructs new {@link TextComponentState} with settings from {@link JTextComponent}.
 *
 * @param textComponent {@link JTextComponent} to retrieve settings from
 */
public TextComponentState ( final JTextComponent textComponent )
{
    this ( textComponent.getText (), textComponent.getCaretPosition () );
}