类javax.swing.text.JTextComponent源码实例Demo

下面列出了怎么用javax.swing.text.JTextComponent的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: pumpernickel   文件: TextContextualMenuHelper.java
/**
 * 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("");
					}
				});
	}
}
 
源代码2 项目: netbeans   文件: SetProperty.java
@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;
}
 
源代码3 项目: netbeans   文件: ProjectEditorSupportImpl.java
@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;
}
 
源代码4 项目: netbeans   文件: EditorRegistry.java
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));
}
 
源代码5 项目: netbeans   文件: CodeTemplateCompletionProvider.java
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);
}
 
源代码6 项目: filthy-rich-clients   文件: FadingDemo.java
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();
}
 
源代码7 项目: ats-framework   文件: SwingElementState.java
/**
 * 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;
    }
}
 
源代码8 项目: jdal   文件: DefaultsBeanDefinitionParser.java
/**
 * @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;
}
 
源代码9 项目: netbeans   文件: NbToolTip.java
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;
}
 
源代码10 项目: netbeans   文件: IMGCustomizer.java
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;
            }
        }
    );
            
}
 
源代码11 项目: TencentKona-8   文件: SwingUtilities2.java
/**
 * 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;
}
 
源代码12 项目: netbeans   文件: AbbrevDetection.java
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;
}
 
源代码13 项目: visualvm   文件: ActionUtils.java
/**
 * 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;
}
 
源代码14 项目: netbeans   文件: CompletionLayoutPopup.java
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
}
 
源代码15 项目: java-swing-tips   文件: MainPanel.java
@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("");
  }
}
 
源代码16 项目: netbeans   文件: DocumentViewOp.java
@Override
public void stateChanged(ChangeEvent e) {
    // First lock document and then monitor
    JTextComponent textComponent = docView.getTextComponent();
    if (textComponent != null) {
        updateVisibleDimension(false);
    }
}
 
源代码17 项目: dragonwell8_jdk   文件: AquaTextFieldSearch.java
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); }
        });
    }
}
 
源代码18 项目: netbeans   文件: AnnotationBarManager.java
/**
 * 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;
}
 
源代码19 项目: netbeans   文件: EditorRegistry.java
private static JTextComponent firstValidComponent() {
    JTextComponent c = null;
    while (items != null && (c = items.get()) == null) {
        removeFromItemList(items);
    }
    return c;
}
 
源代码20 项目: openjdk-jdk8u   文件: TransferHandler.java
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);
    }
}
 
源代码21 项目: netbeans   文件: JavaHyperlinkProvider.java
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;
    }
}
 
源代码22 项目: netbeans   文件: EqualsHashCodeGenerator.java
/** 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;
    
}
 
源代码23 项目: netbeans   文件: BaseTable.java
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();
            }
        }
    }
}
 
源代码24 项目: energy2d   文件: TextComponentPopupMenu.java
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);

	}
 
源代码25 项目: ganttproject   文件: TreeTableCellEditorImpl.java
static Runnable createSelectAllCommand(final JTextComponent textComponent) {
  return createOnFocusGained(textComponent, new Runnable() {
    @Override
    public void run() {
      textComponent.selectAll();
    }
  });
}
 
源代码26 项目: snap-desktop   文件: UIUtils.java
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);
    }
}
 
源代码27 项目: netbeans   文件: ExtKit.java
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;
}
 
源代码28 项目: jdk8u-dev-jdk   文件: CAccessibleText.java
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);
}
 
源代码29 项目: jdk8u_jdk   文件: MultiTextUI.java
@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;
}
 
源代码30 项目: netbeans   文件: AttributeResultItem.java
@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;
}
 
 类所在包
 同包方法