Java Code Examples for javax.swing.text.JTextComponent

The following examples show how to use javax.swing.text.JTextComponent. These examples are extracted from open source projects. 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 Project: pumpernickel   Source File: TextContextualMenuHelper.java    License: MIT License 6 votes vote down vote up
/**
 * Install some basic contextual menu items for a JTextComponent. Note Swing
 * already implements most basic commands, so the implementation is not
 * written here. This only applies a simple UI to existing functionality,
 * because some users won't know to try ctrl-C to copy.
 * 
 * @param jtc
 *            the text component to install contextual menu items on.
 * @param copy
 *            whether "Copy" should be included.
 * @param cut
 *            whether "Cut" should be included.
 * @param paste
 *            whether "Paste" should be included.
 * @param clear
 *            whether "Clear" should be included.
 */
public static void install(final JTextComponent jtc, boolean copy,
		boolean cut, boolean paste, boolean clear) {
	if (cut) {
		install(jtc, "cut", "cut");
	}
	if (copy) {
		install(jtc, "copy", "copy");
	}
	if (paste) {
		install(jtc, "paste", "paste");
	}
	if (clear) {
		ContextualMenuHelper.add(jtc, strings.getString("clear"),
				new Runnable() {
					public void run() {
						jtc.setText("");
					}
				});
	}
}
 
Example 2
Source Project: netbeans   Source File: SetProperty.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleTransfer(JTextComponent targetComponent) {
    allBeans = initAllBeans(targetComponent);
    SetPropertyCustomizer c = new SetPropertyCustomizer(this, targetComponent);
    boolean accept = c.showDialog();
    if (accept) {
        String body = createBody();
        try {
            JspPaletteUtilities.insert(body, targetComponent);
        } catch (BadLocationException ble) {
            accept = false;
        }
    }

    return accept;
}
 
Example 3
Source Project: netbeans   Source File: ProjectEditorSupportImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int getCurrentOffset() {
    try {
        return performOnAWT(new Callable<Integer>() {

            @Override
            public Integer call() throws Exception {
                JTextComponent mostActiveEditor = EditorRegistry.lastFocusedComponent();

                if ((mostActiveEditor != null) && (mostActiveEditor.getCaret() != null)) {
                    return mostActiveEditor.getCaretPosition();
                }

                return -1;
            }
        });
    } catch (Exception e) {
        Exceptions.printStackTrace(e);
    }
    return -1;
}
 
Example 4
Source Project: netbeans   Source File: EditorRegistry.java    License: Apache License 2.0 6 votes vote down vote up
private synchronized static void _focusGained(JTextComponent c, Component origFocused, List<PropertyChangeEvent> events) {
    Item item = item(c);
    assert (item != null) : "Not registered!"; // NOI18N

    // Move the item to head of the list
    removeFromItemList(item);
    addToItemListAsFirst(item);
    item.focused = true;

    c.addPropertyChangeListener(PropertyDocL.INSTANCE);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.log(Level.FINE, FOCUS_GAINED_PROPERTY + ": " + dumpComponent(c) + '\n'); //NOI18N
        logItemListFinest();
    }
    if (c == origFocused) {
        origFocused = null;
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("has equal components, using origFocused = "+origFocused);
        }
    }
    events.add(new PropertyChangeEvent(EditorRegistry.class, FOCUS_GAINED_PROPERTY, origFocused, c));
}
 
Example 5
Source Project: netbeans   Source File: CodeTemplateCompletionProvider.java    License: Apache License 2.0 6 votes vote down vote up
protected @Override boolean canFilter(JTextComponent component) {
    if (component.getCaret() == null) {
        return false;
    }
    int caretOffset = component.getSelectionStart();
    Document doc = component.getDocument();
    filterPrefix = null;
    if (caretOffset >= queryCaretOffset) {
        if (queryAnchorOffset < queryCaretOffset) {
            try {
                filterPrefix = doc.getText(queryAnchorOffset, caretOffset - queryAnchorOffset);
                if (!isJavaIdentifierPart(filterPrefix)) {
                    filterPrefix = null;
                }
            } catch (BadLocationException e) {
                // filterPrefix stays null -> no filtering
            }
        }
    }
    return (filterPrefix != null);
}
 
Example 6
public static void setTextAndAnimate(final JTextComponent textComponent,
        final String text) {
   Color c = textComponent.getForeground();

   KeyFrames keyFrames = new KeyFrames(KeyValues.create(
               new Color(c.getRed(), c.getGreen(), c.getBlue(), 255),
               new Color(c.getRed(), c.getGreen(), c.getBlue(), 0),
               new Color(c.getRed(), c.getGreen(), c.getBlue(), 255)
           ));
   PropertySetter setter = new PropertySetter(textComponent, "foreground",
           keyFrames);

   Animator animator = new Animator(200, setter);
   animator.addTarget(new TimingTargetAdapter() {
       private boolean textSet = false;

       public void timingEvent(float fraction) {
           if (fraction >= 0.5f && !textSet) {
               textComponent.setText(text);
               textSet = true;
           }
       } 
   });
   animator.start();
}
 
Example 7
Source Project: ats-framework   Source File: SwingElementState.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check if the element is editable or not
 *
 * @return if the element is editable or not
 */
@PublicAtsApi
public boolean isElementEditable() {

    try {

        Component component = SwingElementLocator.findFixture(element).component();
        if (component instanceof JTextComponent) {
            return ((JTextComponent) component).isEditable();
        } else if (component instanceof JComboBox) {
            return ((JComboBox) component).isEditable();
        } else if (component instanceof JTree) {
            return ((JTree) component).isEditable();
        }
        throw new NotSupportedOperationException("Component of type \"" + component.getClass().getName()
                                                 + "\" doesn't have 'editable' state!");
    } catch (ElementNotFoundException nsee) {
        lastNotFoundException = nsee;
        return false;
    }
}
 
Example 8
Source Project: jdal   Source File: DefaultsBeanDefinitionParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return
 */
private ComponentDefinition registerAccessorFactory(Element element, ParserContext parserContext) {
	BeanDefinitionBuilder bdb = BeanDefinitionBuilder.genericBeanDefinition(
			ConfigurableControlAccessorFactory.class);
	
	Map<Class<?>, Class<?extends ControlAccessor>> accessors = 
			new ManagedMap<Class<?>,Class<?extends ControlAccessor>>();
	accessors.put(JTextComponent.class, TextComponentAccessor.class);
	accessors.put(JList.class, ListAccessor.class);
	accessors.put(Selector.class, SelectorAccessor.class);
	accessors.put(JToggleButton.class, ToggleButtonAccessor.class);
	accessors.put(JComboBox.class, ComboAccessor.class);
	accessors.put(View.class, ViewAccessor.class);
	accessors.put(JLabel.class, LabelAccessor.class);
	accessors.put(TablePanel.class, TablePanelAccessor.class);
	bdb.addPropertyValue("accessors", accessors);
	
	BeanComponentDefinition bcd = new BeanComponentDefinition(bdb.getBeanDefinition(), ACCESSOR_FACTORY_BEAN_NAME);
	
	registerBeanComponentDefinition(element, parserContext, bcd);	
	return bcd;
}
 
Example 9
Source Project: netbeans   Source File: NbToolTip.java    License: Apache License 2.0 6 votes vote down vote up
Request(
    AnnotationDesc annoDesc, Annotation[] annos, Line.Part lp,
    int offset, Object tooltipAttributeValue,
    ToolTipSupport tts, JTextComponent component, AbstractDocument doc, NbEditorKit kit, int requestId
) {
    this.annoDesc = annoDesc;
    this.annos = annos;
    this.linePart = lp;
    this.tts = tts;
    this.component = component;
    this.doc = doc;
    this.kit = kit;
    this.offset = offset;
    this.tooltipAttributeValue = tooltipAttributeValue;
    this.requestId = requestId;
}
 
Example 10
Source Project: netbeans   Source File: IMGCustomizer.java    License: Apache License 2.0 6 votes vote down vote up
public IMGCustomizer(IMG img, JTextComponent target) {
    this.img = img;
    this.target = target;
    
    initComponents();

    jFileChooser1.setAcceptAllFileFilterUsed(false);
    jFileChooser1.addChoosableFileFilter(
        new FileFilter() {
            public boolean accept(File pathname) {
                FileObject fo = FileUtil.toFileObject(pathname);
                return pathname.isDirectory() || (fo != null && fo.getMIMEType().startsWith("image/")); // NOI18N
            }
            public String getDescription() {
                String desc = NbBundle.getMessage(IMGCustomizer.class, "LBL_IMG_FileChooserDesc");
                return desc;
            }
        }
    );
            
}
 
Example 11
/**
 * Determines whether the SelectedTextColor should be used for painting text
 * foreground for the specified highlight.
 *
 * Returns true only if the highlight painter for the specified highlight
 * is the swing painter (whether inner class of javax.swing.text.DefaultHighlighter
 * or com.sun.java.swing.plaf.windows.WindowsTextUI) and its background color
 * is null or equals to the selection color of the text component.
 *
 * This is a hack for fixing both bugs 4761990 and 5003294
 */
public static boolean useSelectedTextColor(Highlighter.Highlight h, JTextComponent c) {
    Highlighter.HighlightPainter painter = h.getPainter();
    String painterClass = painter.getClass().getName();
    if (painterClass.indexOf("javax.swing.text.DefaultHighlighter") != 0 &&
            painterClass.indexOf("com.sun.java.swing.plaf.windows.WindowsTextUI") != 0) {
        return false;
    }
    try {
        DefaultHighlighter.DefaultHighlightPainter defPainter =
                (DefaultHighlighter.DefaultHighlightPainter) painter;
        if (defPainter.getColor() != null &&
                !defPainter.getColor().equals(c.getSelectionColor())) {
            return false;
        }
    } catch (ClassCastException e) {
        return false;
    }
    return true;
}
 
Example 12
Source Project: netbeans   Source File: AbbrevDetection.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean expand(CodeTemplateManagerOperation op, JTextComponent component, int abbrevStartOffset, CharSequence abbrev) {
    op.waitLoaded();
    CodeTemplate ct = op.findByAbbreviation(abbrev.toString());
    if (ct != null) {
        if (accept(ct, CodeTemplateManagerOperation.getTemplateFilters(component, abbrevStartOffset))) {
            Document doc = component.getDocument();
            sendUndoableEdit(doc, CloneableEditorSupport.BEGIN_COMMIT_GROUP);
            try {
                // Remove the abbrev text
                doc.remove(abbrevStartOffset, abbrev.length());
                ct.insert(component);
            } catch (BadLocationException ble) {
            } finally {
                sendUndoableEdit(doc, CloneableEditorSupport.END_COMMIT_GROUP);
            }
            return true;
        }
    }
    return false;
}
 
Example 13
Source Project: visualvm   Source File: ActionUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the line of text at the given position.  The returned value may
 * be null.  It will not contain the trailing new-line character.
 * @param target the text component
 * @param pos char position
 * @return
 */
public static String getLineAt(JTextComponent target, int pos) {
    String line = null;
    Document doc = target.getDocument();
    if (doc instanceof PlainDocument) {
        PlainDocument pDoc = (PlainDocument) doc;
        int start = pDoc.getParagraphElement(pos).getStartOffset();
        int end = pDoc.getParagraphElement(pos).getEndOffset();
        try {
            line = doc.getText(start, end - start);
            if (line != null && line.endsWith("\n")) {
                line = line.substring(0, line.length() - 1);
            }
        } catch (BadLocationException ex) {
            Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return line;
}
 
Example 14
Source Project: netbeans   Source File: CompletionLayoutPopup.java    License: Apache License 2.0 6 votes vote down vote up
public void show(JTextComponent editorComponent, int anchorOffset) {
    if (editorComponent == null || ClipboardHistory.getInstance().getData().isEmpty()) {
        return;
    }

    if (!isVisible()) { // documentation already visible
        ScrollCompletionPane scrollCompletionPane = new ScrollCompletionPane(editorComponent, ClipboardHistory.getInstance(), null, chSelectionListener, mouseListener);
        scrollCompletionPane.setName(POPUP_NAME);
        setContentComponent(scrollCompletionPane);
        setLayout(scrollCompletionPane);   
        setEditorComponent(editorComponent);
    }

    if (!isVisible()) { // do not check for size as it should remain the same
        // Set anchoring only if not displayed yet because completion
        // may have overriden the anchoring
        setAnchorOffset(anchorOffset);
        updateLayout(this);
        chSelectionListener.valueChanged(null);
        
    } // otherwise leave present doc displayed
}
 
Example 15
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 5 votes vote down vote up
@Override public void focusGained(FocusEvent e) {
  JTextComponent tf = (JTextComponent) e.getComponent();
  if (hintMessage.equals(tf.getText()) && INACTIVE.equals(tf.getForeground())) {
    tf.setForeground(UIManager.getColor("TextField.foreground"));
    tf.setText("");
  }
}
 
Example 16
Source Project: netbeans   Source File: DocumentViewOp.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void stateChanged(ChangeEvent e) {
    // First lock document and then monitor
    JTextComponent textComponent = docView.getTextComponent();
    if (textComponent != null) {
        updateVisibleDimension(false);
    }
}
 
Example 17
static void updatePromptLabel(final JLabel label, final JTextComponent text) {
    if (SwingUtilities.isEventDispatchThread()) {
        updatePromptLabelOnEDT(label, text);
    } else {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() { updatePromptLabelOnEDT(label, text); }
        });
    }
}
 
Example 18
Source Project: netbeans   Source File: AnnotationBarManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Shows annotations sidebar.
 */
public static AnnotationBar showAnnotationBar(JTextComponent target, List<Location> locations) {
    AnnotationBar ab = (AnnotationBar) target.getClientProperty(BAR_KEY);
    assert ab != null;
    ab.annotate(locations);
    return ab;
}
 
Example 19
Source Project: netbeans   Source File: EditorRegistry.java    License: Apache License 2.0 5 votes vote down vote up
private static JTextComponent firstValidComponent() {
    JTextComponent c = null;
    while (items != null && (c = items.get()) == null) {
        removeFromItemList(items);
    }
    return c;
}
 
Example 20
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 21
Source Project: netbeans   Source File: JavaHyperlinkProvider.java    License: Apache License 2.0 5 votes vote down vote up
public void performClickAction(Document doc, int offset, HyperlinkType type) {
    switch (type) {
        case GO_TO_DECLARATION:
            GoToSupport.goTo(doc, offset, false);
            break;
        case ALT_HYPERLINK:
            JTextComponent focused = EditorRegistry.focusedComponent();
            
            if (focused != null && focused.getDocument() == doc) {
                focused.setCaretPosition(offset);
                GoToImplementation.goToImplementation(focused);
            }
            break;
    }
}
 
Example 22
Source Project: netbeans   Source File: EqualsHashCodeGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/** Creates a new instance of EqualsHashCodeGenerator */
private EqualsHashCodeGenerator(JTextComponent component, ElementNode.Description description, boolean generateEquals, boolean generateHashCode) {
    this.component = component;
    this.description = description;        
    this.generateEquals = generateEquals;
    this.generateHashCode = generateHashCode;
    
}
 
Example 23
Source Project: netbeans   Source File: BaseTable.java    License: Apache License 2.0 5 votes vote down vote up
private void trySendEnterToDialog(BaseTable bt) {
    //        System.err.println("SendEnterToDialog");
    EventObject ev = EventQueue.getCurrentEvent();

    if (ev instanceof KeyEvent && (((KeyEvent) ev).getKeyCode() == KeyEvent.VK_ENTER)) {
        if (ev.getSource() instanceof JComboBox && ((JComboBox) ev.getSource()).isPopupVisible()) {
            return;
        }

        if (
            ev.getSource() instanceof JTextComponent &&
                ((JTextComponent) ev.getSource()).getParent() instanceof JComboBox &&
                ((JComboBox) ((JTextComponent) ev.getSource()).getParent()).isPopupVisible()
        ) {
            return;
        }

        JRootPane jrp = bt.getRootPane();

        if (jrp != null) {
            JButton b = jrp.getDefaultButton();

            if ((b != null) && b.isEnabled()) {
                b.doClick();
            }
        }
    }
}
 
Example 24
public TextComponentPopupMenu(JTextComponent t) {

		text = t;

		actions = new HashMap<Object, Action>();
		for (Action act : text.getActions())
			actions.put(act.getValue(Action.NAME), act);

		boolean isMac = System.getProperty("os.name").startsWith("Mac");

		miCopy = new JMenuItem(actions.get(DefaultEditorKit.copyAction));
		miCopy.setText("Copy");
		miCopy.setAccelerator(isMac ? KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.META_MASK) : KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_MASK));
		add(miCopy);

		miCut = new JMenuItem(actions.get(DefaultEditorKit.cutAction));
		miCut.setText("Cut");
		miCut.setAccelerator(isMac ? KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.META_MASK) : KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.CTRL_MASK));
		add(miCut);

		miPaste = new JMenuItem(actions.get(DefaultEditorKit.pasteAction));
		miPaste.setText("Paste");
		miPaste.setAccelerator(isMac ? KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.META_MASK) : KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.CTRL_MASK));
		add(miPaste);

		miSelectAll = new JMenuItem(actions.get(DefaultEditorKit.selectAllAction));
		miSelectAll.setText("Select All");
		miSelectAll.setAccelerator(isMac ? KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.META_MASK) : KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_MASK));
		add(miSelectAll);

	}
 
Example 25
static Runnable createSelectAllCommand(final JTextComponent textComponent) {
  return createOnFocusGained(textComponent, new Runnable() {
    @Override
    public void run() {
      textComponent.selectAll();
    }
  });
}
 
Example 26
Source Project: snap-desktop   Source File: UIUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void addPromptSupport(JComponent component, String text) {
    if (JTextComponent.class.isAssignableFrom(component.getClass())) {
        JTextComponent castedComponent = (JTextComponent) component;
        PromptSupport.setPrompt(text, castedComponent);
        PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.HIDE_PROMPT, castedComponent);
    }
}
 
Example 27
Source Project: netbeans   Source File: ExtKit.java    License: Apache License 2.0 5 votes vote down vote up
protected String getItemText(JTextComponent target, String actionName, Action a) {
    String itemText;
    if (a instanceof BaseAction) {
        itemText = ((BaseAction)a).getPopupMenuText(target);
    } else {
        itemText = (String) a.getValue("popupText");
        if (itemText == null) {
            itemText = (String) a.getValue("menuText");
            if (itemText == null) {
                itemText = actionName;
            }
        }
    }
    return itemText;
}
 
Example 28
static int getLineNumberForIndex(final Accessible a, int index) {
    final Accessible sa = CAccessible.getSwingAccessible(a);
    if (!(sa instanceof JTextComponent)) return -1;

    final JTextComponent jc = (JTextComponent) sa;
    final Element root = jc.getDocument().getDefaultRootElement();

    // treat -1 special, returns the current caret position
    if (index == -1) index = jc.getCaretPosition();

    // Determine line number (can be -1)
    return root.getElementIndex(index);
}
 
Example 29
Source Project: jdk8u_jdk   Source File: MultiTextUI.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public int viewToModel2D(JTextComponent a, Point2D b, Position.Bias[] c) {
    int returnValue =
        ((TextUI) (uis.elementAt(0))).viewToModel2D(a,b,c);
    for (int i = 1; i < uis.size(); i++) {
        ((TextUI) (uis.elementAt(i))).viewToModel2D(a,b,c);
    }
    return returnValue;
}
 
Example 30
Source Project: netbeans   Source File: AttributeResultItem.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected int removeTextLength(JTextComponent component, int offset, int removeLength) {
    if (removeLength <= 0) {
        return super.removeTextLength(component, offset, removeLength);
    }
    TokenSequence s = createTokenSequence(component);
    s.move(offset);
    if (!s.moveNext()) {
        return super.removeTextLength(component, offset, removeLength);
    }
    TokenId id = s.token().id();
    if (id != XMLTokenId.ARGUMENT) {
        return s.token().length() - (offset - s.offset());
    }
    int l = s.offset() + s.token().length();
    while (s.moveNext()) {
        id = s.token().id();
        if (id== XMLTokenId.VALUE) {
            // remove up to and including the quote
            return s.offset() - offset + 1;
        } else if (!(id == XMLTokenId.WS || id == XMLTokenId.OPERATOR)) {
            break;
        }
        l = s.offset() + s.token().length();
    }
    return l - offset;
}