Пример #1
0
  /*
   *  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;
  }
Пример #2
0
  /**
   * 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;
  }
Пример #3
0
  // ------------------------------------------------------------------
  // 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
Пример #4
0
 /**
  * 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;
 }
    /**
     * Paints a highlight.
     *
     * @param g the graphics context
     * @param offs0 the starting model offset &gt;= 0
     * @param offs1 the ending model offset &gt;= 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
      }
    }
Пример #6
0
 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
   }
 }
Пример #7
0
 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) {
   }
 }
Пример #8
0
  protected void uninstallListeners() {
    final JTextComponent c = getComponent();
    AquaTextFieldSearch.uninstallSearchFieldListener(c);
    AquaUtilControlSize.removeSizePropertyListener(c);
    c.removeFocusListener(handler);
    c.removePropertyChangeListener(handler);
    handler = null;

    super.uninstallListeners();
  }
Пример #9
0
 @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);
   }
 }
Пример #10
0
  /** 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;
    }
  }
Пример #11
0
    public void actionPerformed(ActionEvent e) {
      JTextComponent textComponent = getTextComponent(e);
      if (!textComponent.isEditable() || !textComponent.isEnabled()) {
        return;
      }

      try {
        outdentText(textComponent);
      } catch (BadLocationException e1) {
        e1.printStackTrace();
      }
    }
Пример #12
0
  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);
  }
Пример #13
0
  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);
    }
  }
Пример #14
0
    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);
      }
    }
Пример #15
0
  /**
   * 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);
  }
Пример #16
0
  //
  //  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;
    }
  }
Пример #17
0
 /**
  * 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;
 }
  // 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;
  }
Пример #19
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);
  }
 /**
  * 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 ###
   }
 }
Пример #21
0
  //    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();
    }
  }
Пример #22
0
  /** 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() : "");
  }
Пример #23
0
  @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;
  }
Пример #25
0
  /**
   * 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();
  }
Пример #26
0
  /*
   *	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");
  }
Пример #28
0
 /** Select or grow image when clicked. */
 public void mousePressed(MouseEvent e) {
   Dimension size = fComponent.getSize();
   if (e.getX() >= size.width - 7 && e.getY() >= size.height - 7 && getSelectionState() == 2) {
     // Click in selected grow-box:
     if (DEBUG) System.out.println("ImageView: grow!!! Size=" + fWidth + "x" + fHeight);
     Point loc = fComponent.getLocationOnScreen();
     fGrowBase = new Point(loc.x + e.getX() - fWidth, loc.y + e.getY() - fHeight);
     fGrowProportionally = e.isShiftDown();
   } else {
     // Else select image:
     fGrowBase = null;
     JTextComponent comp = (JTextComponent) fContainer;
     int start = fElement.getStartOffset();
     int end = fElement.getEndOffset();
     int mark = comp.getCaret().getMark();
     int dot = comp.getCaret().getDot();
     if (e.isShiftDown()) {
       // extend selection if shift key down:
       if (mark <= start) comp.moveCaretPosition(end);
       else comp.moveCaretPosition(start);
     } else {
       // just select image, without shift:
       if (mark != start) comp.setCaretPosition(start);
       if (dot != end) comp.moveCaretPosition(end);
     }
   }
 }
Пример #29
0
 void removeText() {
   if ((p0 != null) && (p1 != null) && (p0.getOffset() != p1.getOffset())) {
     try {
       Document doc = c.getDocument();
       doc.remove(p0.getOffset(), p1.getOffset() - p0.getOffset());
     } catch (BadLocationException e) {
     }
   }
 }
 public void setEnabled(boolean enabled) {
   textComponent.setEnabled(enabled);
   //
   if (showToolbar) {
     for (int i = 0; i < toolbarButtons.length; i++) {
       toolbarButtons[i].setEnabled(enabled);
     }
   }
 }