// ------------------------------------------------------------------ // from Java Swing 1.2 Orielly - Robert Eckstein // ------------------------------------------------------------------ protected JTextComponent updateKeymapForWord(JTextComponent textComp) { // create a new child keymap Keymap map = JTextComponent.addKeymap("NslmMap", textComp.getKeymap()); // define the keystrokeds to be added KeyStroke next = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.CTRL_MASK, false); // add the new mappings used DefaultEditorKit actions map.addActionForKeyStroke(next, getAction(DefaultEditorKit.nextWordAction)); KeyStroke prev = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.CTRL_MASK, false); map.addActionForKeyStroke(prev, getAction(DefaultEditorKit.previousWordAction)); KeyStroke selNext = KeyStroke.getKeyStroke( KeyEvent.VK_RIGHT, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK, false); map.addActionForKeyStroke(selNext, getAction(DefaultEditorKit.selectionNextWordAction)); KeyStroke selPrev = KeyStroke.getKeyStroke( KeyEvent.VK_LEFT, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK, false); map.addActionForKeyStroke(selPrev, getAction(DefaultEditorKit.selectionPreviousWordAction)); KeyStroke find = KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_MASK, false); map.addActionForKeyStroke(find, getAction("find")); KeyStroke findAgain = KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_MASK, false); map.addActionForKeyStroke(findAgain, getAction("findAgain")); // set the keymap for the text component textComp.setKeymap(map); return (textComp); } // end updateKeymapForWord
/** * This method causes a transfer to a component from a clipboard or a DND drop operation. The * Transferable represents the data to be imported into the component. * * @param comp The component to receive the transfer. This argument is provided to enable sharing * of TransferHandlers by multiple components. * @param t The data to import * @return <code>true</code> iff the data was inserted into the component. */ public boolean importData(JComponent comp, Transferable t) { JTextComponent c = (JTextComponent) comp; withinSameComponent = c == exportComp; // if we are importing to the same component that we exported from // then don't actually do anything if the drop location is inside // the drag location and set shouldRemove to false so that exportDone // knows not to remove any data if (withinSameComponent && c.getCaretPosition() >= p0 && c.getCaretPosition() <= p1) { shouldRemove = false; return true; } boolean imported = false; DataFlavor importFlavor = getImportFlavor(t.getTransferDataFlavors(), c); if (importFlavor != null) { try { InputContext ic = c.getInputContext(); if (ic != null) ic.endComposition(); Reader r = importFlavor.getReaderForText(t); handleReaderImport(r, c); imported = true; } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); } catch (BadLocationException ble) { ble.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } return imported; }
/** * Paints a highlight. * * @param g the graphics context * @param offs0 the starting model offset >= 0 * @param offs1 the ending model offset >= offs1 * @param bounds the bounding box for the highlight * @param c the editor */ public void paint(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c) { Rectangle alloc = bounds.getBounds(); try { // --- determine locations --- TextUI mapper = c.getUI(); Rectangle p0 = mapper.modelToView(c, offs0); Rectangle p1 = mapper.modelToView(c, offs1); // --- render --- Color color = getColor(); if (color == null) { g.setColor(c.getSelectionColor()); } else { g.setColor(color); } if (p0.y == p1.y) { // same line, render a rectangle Rectangle r = p0.union(p1); g.fillRect(r.x, r.y, r.width, r.height); } else { // different lines int p0ToMarginWidth = alloc.x + alloc.width - p0.x; g.fillRect(p0.x, p0.y, p0ToMarginWidth, p0.height); if ((p0.y + p0.height) != p1.y) { g.fillRect(alloc.x, p0.y + p0.height, alloc.width, p1.y - (p0.y + p0.height)); } g.fillRect(alloc.x, p1.y, (p1.x - alloc.x), p1.height); } } catch (BadLocationException e) { // can't render } }
/* */ public void paint(Graphics paramGraphics, Shape paramShape) /* */ { /* 579 */ Rectangle localRectangle = (Rectangle) paramShape; /* 580 */ int i = localRectangle.y + WrappedPlainView.this.metrics.getAscent(); /* 581 */ int j = localRectangle.x; /* */ /* 583 */ JTextComponent localJTextComponent = (JTextComponent) getContainer(); /* 584 */ Highlighter localHighlighter = localJTextComponent.getHighlighter(); /* 585 */ Object localObject = (localHighlighter instanceof LayeredHighlighter) ? (LayeredHighlighter) localHighlighter : null; /* */ /* 588 */ int k = getStartOffset(); /* 589 */ int m = getEndOffset(); /* 590 */ int n = k; /* 591 */ int[] arrayOfInt = getLineEnds(); /* 592 */ for (int i1 = 0; i1 < this.lineCount; i1++) { /* 593 */ int i2 = arrayOfInt == null ? m : k + arrayOfInt[i1]; /* */ /* 595 */ if (localObject != null) { /* 596 */ int i3 = i2 == m ? i2 - 1 : i2; /* */ /* 599 */ localObject.paintLayeredHighlights( paramGraphics, n, i3, paramShape, localJTextComponent, this); /* */ } /* 601 */ WrappedPlainView.this.drawLine(n, i2, paramGraphics, j, i); /* */ /* 603 */ n = i2; /* 604 */ i += WrappedPlainView.this.metrics.getHeight(); /* */ } /* */ }
/* * We need to know if the caret is currently positioned on the line we * are about to paint so the line number can be highlighted. */ private boolean isCurrentLine(int rowStartOffset) { int caretPosition = component.getCaretPosition(); Element root = component.getDocument().getDefaultRootElement(); if (root.getElementIndex(rowStartOffset) == root.getElementIndex(caretPosition)) return true; else return false; }
/** * Create a Transferable to use as the source for a data transfer. * * @param comp The component holding the data to be transfered. This argument is provided to * enable sharing of TransferHandlers by multiple components. * @return The representation of the data to be transfered. */ protected Transferable createTransferable(JComponent comp) { exportComp = (JTextComponent) comp; shouldRemove = true; p0 = exportComp.getSelectionStart(); p1 = exportComp.getSelectionEnd(); return (p0 != p1) ? (new TextTransferable(exportComp, p0, p1)) : null; }
/** * Provides a way to determine the next visually represented model location at which one might * place a caret. Some views may not be visible, they might not be in the same order found in the * model, or they just might not allow access to some of the locations in the model. * * @param pos the position to convert >= 0 * @param a the allocated region in which to render * @param direction the direction from the current position that can be thought of as the arrow * keys typically found on a keyboard. This will be one of the following values: * <ul> * <li>SwingConstants.WEST * <li>SwingConstants.EAST * <li>SwingConstants.NORTH * <li>SwingConstants.SOUTH * </ul> * * @return the location within the model that best represents the next location visual position * @exception BadLocationException * @exception IllegalArgumentException if <code>direction</code> doesn't have one of the legal * values above */ public int getNextVisualPositionFrom( int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) throws BadLocationException { biasRet[0] = Position.Bias.Forward; switch (direction) { case NORTH: case SOUTH: { if (pos == -1) { pos = (direction == NORTH) ? Math.max(0, getEndOffset() - 1) : getStartOffset(); break; } JTextComponent target = (JTextComponent) getContainer(); Caret c = (target != null) ? target.getCaret() : null; // YECK! Ideally, the x location from the magic caret position // would be passed in. Point mcp; if (c != null) { mcp = c.getMagicCaretPosition(); } else { mcp = null; } int x; if (mcp == null) { Rectangle loc = target.modelToView(pos); x = (loc == null) ? 0 : loc.x; } else { x = mcp.x; } if (direction == NORTH) { pos = Utilities.getPositionAbove(target, pos, x); } else { pos = Utilities.getPositionBelow(target, pos, x); } } break; case WEST: if (pos == -1) { pos = Math.max(0, getEndOffset() - 1); } else { pos = Math.max(0, pos - 1); } break; case EAST: if (pos == -1) { pos = getStartOffset(); } else { pos = Math.min(pos + 1, getDocument().getLength()); } break; default: throw new IllegalArgumentException("Bad direction: " + direction); } return pos; }
protected void uninstallListeners() { final JTextComponent c = getComponent(); AquaTextFieldSearch.uninstallSearchFieldListener(c); AquaUtilControlSize.removeSizePropertyListener(c); c.removeFocusListener(handler); c.removePropertyChangeListener(handler); handler = null; super.uninstallListeners(); }
public void insertBreak(JTextComponent text) { indentationLogic = ((EditorPane) text).getIndentationLogic(); boolean noSelection = text.getSelectionStart() == text.getSelectionEnd(); if (noSelection) { insertNewlineWithAutoIndent(text); } else { text.replaceSelection("\n"); // TODO insertNewlineWithAutoIndent } }
TextTransferable(JTextComponent c, int start, int end) { this.c = c; Document doc = c.getDocument(); try { p0 = doc.createPosition(start); p1 = doc.createPosition(end); plainData = c.getSelectedText(); } catch (BadLocationException ble) { } }
@Override public void show(Component c, int x, int y) { if (c instanceof JTextComponent) { JTextComponent textArea = (JTextComponent) c; boolean flg = Objects.nonNull(textArea.getSelectedText()); cutAction.setEnabled(flg); copyAction.setEnabled(flg); deleteAction.setEnabled(flg); super.show(c, x, y); } }
protected void installListeners() { super.installListeners(); handler = new AquaFocusHandler(); final JTextComponent c = getComponent(); c.addFocusListener(handler); c.addPropertyChangeListener(handler); LookAndFeel.installProperty(c, "opaque", UIManager.getBoolean(getPropertyPrefix() + "opaque")); AquaUtilControlSize.addSizePropertyListener(c); AquaTextFieldSearch.installSearchFieldListener(c); }
public void actionPerformed(ActionEvent e) { JTextComponent textComponent = getTextComponent(e); if (!textComponent.isEditable() || !textComponent.isEnabled()) { return; } try { outdentText(textComponent); } catch (BadLocationException e1) { e1.printStackTrace(); } }
/** See if edit value is valid, put error message in buff. */ protected boolean _validate(StringBuffer buff) { String editValue = tf.getText().trim(); if (editValue.length() == 0) return true; // empty ok try { new TimeDuration(tf.getText()); return true; } catch (java.text.ParseException e) { buff.append(label).append(": ").append(e.getMessage()); return false; } }
void configureEditor(ComboBoxEditor newEditor) { if (editor != null) { editor.removeKeyListener(editorKeyListener); editor.removeFocusListener(editorFocusListener); } if (newEditor != null) { editor = (JTextComponent) newEditor.getEditorComponent(); editor.addKeyListener(editorKeyListener); editor.addFocusListener(editorFocusListener); editor.setDocument(this); } }
private void outdentText(JTextComponent textComponent) throws BadLocationException { int tabSize = ((Integer) textComponent.getDocument().getProperty(PlainDocument.tabSizeAttribute)) .intValue(); String selectedText = textComponent.getSelectedText(); int newLineIndex = selectedText != null ? selectedText.indexOf('\n') : -1; if (newLineIndex >= 0) { int originalSelectionStart = textComponent.getSelectionStart(); int selectionStart = originalSelectionStart; int selectionEnd = textComponent.getSelectionEnd(); int lastNewLineBeforeSelection = textComponent.getText(0, selectionStart).lastIndexOf('\n'); int begin = lastNewLineBeforeSelection >= 0 ? lastNewLineBeforeSelection : 0; int end = selectionEnd; String text = textComponent.getText(begin, end - begin); if (lastNewLineBeforeSelection < 0) { text = "\n" + text; } int len = text.length(); StringBuffer out = new StringBuffer(len); for (int i = 0; i < len; i++) { char ch = text.charAt(i); out.append(ch); if (ch == '\n' && i < len - 1) { char next = text.charAt(i + 1); int stripCount = 0; if (next == '\t') { stripCount = 1; } else { for (; stripCount < tabSize && i + 1 + stripCount < len; stripCount++) { next = text.charAt(i + 1 + stripCount); if (next != ' ' && next != '\t') { break; } } } selectionEnd -= stripCount; if (i + begin < originalSelectionStart - 1) { selectionStart -= stripCount; } i += stripCount; } } textComponent.select(begin, end); textComponent.replaceSelection( lastNewLineBeforeSelection < 0 ? out.toString().substring(1) : out.toString()); textComponent.select(selectionStart, selectionEnd); } }
// Create a simple JToolBar with some buttons. protected JToolBar createToolBar() { JToolBar bar = new JToolBar(); // Add simple actions for opening & saving. bar.add(getOpenAction()).setText(""); bar.add(getSaveAction()).setText(""); bar.addSeparator(); // Add cut/copy/paste buttons. bar.add(textComp.getActionMap().get(DefaultEditorKit.cutAction)).setText(""); bar.add(textComp.getActionMap().get(DefaultEditorKit.copyAction)).setText(""); bar.add(textComp.getActionMap().get(DefaultEditorKit.pasteAction)).setText(""); return bar; }
/** * Create a line number component for a text component. * * @param argComponent the related text component * @param argMinimumDisplayDigits the number of digits used to calculate the minimum width of the * component. */ public TextLineNumber(JTextComponent argComponent, int argMinimumDisplayDigits) { component = argComponent; setFont(argComponent.getFont()); setBorderGap(5); setCurrentLineForeground(Color.RED); setDigitAlignment(RIGHT); setMinimumDisplayDigits(argMinimumDisplayDigits); argComponent.getDocument().addDocumentListener(this); argComponent.addCaretListener(this); argComponent.addPropertyChangeListener("font", this); }
/** * Determines whether the image is selected, and if it's the only thing selected. * * @return 0 if not selected, 1 if selected, 2 if exclusively selected. "Exclusive" selection is * only returned when editable. */ protected int getSelectionState() { int p0 = fElement.getStartOffset(); int p1 = fElement.getEndOffset(); if (fContainer instanceof JTextComponent) { JTextComponent textComp = (JTextComponent) fContainer; int start = textComp.getSelectionStart(); int end = textComp.getSelectionEnd(); if (start <= p0 && end >= p1) { if (start == p0 && end == p1 && isEditable()) return 2; else return 1; } } return 0; }
@Override public void focusGained(final FocusEvent e) { final JTextComponent component = getComponent(); if (!component.isEnabled() || !component.isEditable()) { super.focusGained(e); return; } mFocused = true; if (!shouldSelectAllOnFocus) { shouldSelectAllOnFocus = true; super.focusGained(e); return; } if (isMultiLineEditor) { super.focusGained(e); return; } final int end = component.getDocument().getLength(); final int dot = getDot(); final int mark = getMark(); if (dot == mark) { if (dot == 0) { component.setCaretPosition(end); component.moveCaretPosition(0); } else if (dot == end) { component.setCaretPosition(0); component.moveCaretPosition(end); } } super.focusGained(e); }
// // Implement CaretListener interface // @Override public void caretUpdate(CaretEvent e) { // Get the line the caret is positioned on int caretPosition = component.getCaretPosition(); Element root = component.getDocument().getDefaultRootElement(); int currentLine = root.getElementIndex(caretPosition); // Need to repaint so the correct line number can be highlighted if (lastLine != currentLine) { repaint(); lastLine = currentLine; } }
/** * References checked: 8.10.2003 (2.0b2) * * @param editorType editor type, one of this constants * <UL> * <LI>EDITOR_TYPE_DEFAULT * <LI>EDITOR_TYPE_STYLED * <LI>EDITOR_TYPE_SINGLE_LINE * </UL> * * @param controler if not <code>null</code> for <code>EDITOR_TYPE_STYLED</code> editors a toolbar * is created * @see PresentationDetail#PresentationDetail */ TextEditorPanel( int editorType, GraphPanelControler controler, boolean showToolbar, PresentationDetail detail) { this.editorType = editorType; this.controler = controler; this.showToolbar = showToolbar; this.detail = detail; setLayout(new BorderLayout()); // --- build this text editor panel --- switch (editorType) { case EDITOR_TYPE_DEFAULT: textComponent = new JTextArea(); add(new JScrollPane(textComponent)); break; case EDITOR_TYPE_STYLED: textComponent = new JTextPane(); textComponent.setTransferHandler(new TextTransferHandler()); // ### requires Java 1.4 // --- add toolbar --- if (showToolbar) { JPanel bar = new JPanel(); Hashtable actions = DeepaMehtaClientUtils.createActionTable(textComponent); bar.setBackground(COLOR_PROPERTY_PANEL); toolbarButtons = new JButton[3]; addButton(bar, new StyledEditorKit.BoldAction(), actions, controler.boldIcon()); addButton(bar, new StyledEditorKit.ItalicAction(), actions, controler.italicIcon()); addButton(bar, new StyledEditorKit.UnderlineAction(), actions, controler.underlineIcon()); // ### addButton(bar, "H1", CMD_SET_HEADLINE1); // ### addButton(bar, "H2", CMD_SET_HEADLINE2); add(bar, BorderLayout.SOUTH); } add(new JScrollPane(textComponent)); break; case EDITOR_TYPE_SINGLE_LINE: textComponent = new JTextField(); ((JTextField) textComponent).addActionListener(this); add(textComponent); break; default: throw new DeepaMehtaException("unexpected text editor type: " + editorType); } // --- enable automatic drag and drop support --- try { textComponent.setDragEnabled(true); } catch (NoSuchMethodError e) { // requires JDK 1.4 ### } }
public PlainView(Document doc, JTextComponent component) { super(doc); this.comp = component; // Subscribe to key presses so we know when to mark the document // as updated comp.addKeyListener( new KeyAdapter() { public void KeyTyped(KeyEvent e) { updateModelFromComponent(comp.getText()); } }); // Subscribe to Document events so we know when to update // the component from the model. doc.addDocumentListener( new DocumentListener() { public void insertUpdate(DocumentEvent e) { updateComponentFromModel(); } public void removeUpdate(DocumentEvent e) { updateComponentFromModel(); } public void changedUpdate(DocumentEvent e) { updateComponentFromModel(); } }); }
// public static final String showElementTreeAction = "showElementTree"; // ------------------------------------------------------------- public void openFile(String currDirStr, String currFileStr) { if (fileDialog == null) { fileDialog = new FileDialog(this); } fileDialog.setMode(FileDialog.LOAD); if (!(currDirStr.equals(""))) { fileDialog.setDirectory(currDirStr); } if (!(currFileStr.equals(""))) { fileDialog.setFile(currFileStr); } fileDialog.show(); String file = fileDialog.getFile(); // cancel pushed if (file == null) { return; } String directory = fileDialog.getDirectory(); File f = new File(directory, file); if (f.exists()) { Document oldDoc = getEditor().getDocument(); if (oldDoc != null) // oldDoc.removeUndoableEditListener(undoHandler); /* if (elementTreePanel != null) { elementTreePanel.setEditor(null); } */ getEditor().setDocument(new PlainDocument()); fileDialog.setTitle(file); Thread loader = new FileLoader(f, editor1.getDocument()); loader.start(); } }
/** Import the given stream data into the text component. */ protected void handleReaderImport(Reader in, JTextComponent c) throws BadLocationException, IOException { char[] buff = new char[1024]; int nch; boolean lastWasCR = false; int last; StringBuffer sbuff = null; // Read in a block at a time, mapping \r\n to \n, as well as single // \r to \n. while ((nch = in.read(buff, 0, buff.length)) != -1) { if (sbuff == null) { sbuff = new StringBuffer(nch); } last = 0; for (int counter = 0; counter < nch; counter++) { switch (buff[counter]) { case '\r': if (lastWasCR) { if (counter == 0) sbuff.append('\n'); else buff[counter - 1] = '\n'; } else lastWasCR = true; break; case '\n': if (lastWasCR) { if (counter > (last + 1)) sbuff.append(buff, last, counter - last - 1); // else nothing to do, can skip \r, next write will // write \n lastWasCR = false; last = counter; } break; default: if (lastWasCR) { if (counter == 0) sbuff.append('\n'); else buff[counter - 1] = '\n'; lastWasCR = false; } break; } // End fo switch (buff[counter]). } // End of for (int counter = 0; counter < nch; counter++). if (last < nch) { if (lastWasCR) { if (last < (nch - 1)) sbuff.append(buff, last, nch - last - 1); } else sbuff.append(buff, last, nch - last); } } // End of while ((nch = in.read(buff, 0, buff.length)) != -1). if (withinSameComponent) { ((RTextArea) c).beginAtomicEdit(); } if (lastWasCR) sbuff.append('\n'); c.replaceSelection(sbuff != null ? sbuff.toString() : ""); }
@Override public void propertyChange(final PropertyChangeEvent evt) { final String propertyName = evt.getPropertyName(); if (AquaFocusHandler.FRAME_ACTIVE_PROPERTY.equals(propertyName)) { final JTextComponent comp = ((JTextComponent) evt.getSource()); if (evt.getNewValue() == Boolean.TRUE) { setVisible(comp.hasFocus()); } else { setVisible(false); } if (getDot() != getMark()) comp.getUI().damageRange(comp, getDot(), getMark()); } }
// Create a JMenuBar with file & edit menus. protected JMenuBar createMenuBar() { JMenuBar menubar = new JMenuBar(); JMenu file = new JMenu("File"); JMenu edit = new JMenu("Edit"); menubar.add(file); menubar.add(edit); file.add(getOpenAction()); file.add(getSaveAction()); file.add(new ExitAction()); edit.add(textComp.getActionMap().get(DefaultEditorKit.cutAction)); edit.add(textComp.getActionMap().get(DefaultEditorKit.copyAction)); edit.add(textComp.getActionMap().get(DefaultEditorKit.pasteAction)); edit.add(textComp.getActionMap().get(DefaultEditorKit.selectAllAction)); return menubar; }
/** * Constructor. * * @param name of the field; must be unique within the store * @param label to display to the user * @param defValue default value to start with. * @param storeData store/fetch data from here, may be null. */ public DurationField( String name, String label, TimeDuration defValue, PersistenceManager storeData) { super(name, label, storeData); validValue = getStoreValue(defValue); tf = new JTextField() { public JToolTip createToolTip() { return new MultilineTooltip(); } }; tf.setToolTipText("Formats:\n udunits time duration string"); tf.setInputVerifier(new FldInputVerifier(tf, this)); if (validValue != null) tf.setText(validValue.toString()); finish(); }
/* * Get the line number to be drawn. The empty string will be returned * when a line of text has wrapped. */ protected String getTextLineNumber(int rowStartOffset) { Element root = component.getDocument().getDefaultRootElement(); int index = root.getElementIndex(rowStartOffset); Element line = root.getElement(index); if (line.getStartOffset() == rowStartOffset) return String.valueOf(index + 1); else return ""; }
// Add icons and friendly names to actions we care about. protected void makeActionsPretty() { Action a; a = textComp.getActionMap().get(DefaultEditorKit.cutAction); a.putValue(Action.SMALL_ICON, new ImageIcon("icons/cut.gif")); a.putValue(Action.NAME, "Cut"); a = textComp.getActionMap().get(DefaultEditorKit.copyAction); a.putValue(Action.SMALL_ICON, new ImageIcon("icons/copy.gif")); a.putValue(Action.NAME, "Copy"); a = textComp.getActionMap().get(DefaultEditorKit.pasteAction); a.putValue(Action.SMALL_ICON, new ImageIcon("icons/paste.gif")); a.putValue(Action.NAME, "Paste"); a = textComp.getActionMap().get(DefaultEditorKit.selectAllAction); a.putValue(Action.NAME, "Select All"); }