private void setText(String text) {
   try {
     // remove all text and insert the completed string
     super.remove(0, getLength());
     super.insertString(0, text, null);
   } catch (BadLocationException e) {
     throw new RuntimeException(e.toString());
   }
 }
 public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
   // return immediately when selecting an item
   if (selecting) {
     return;
   }
   // insert the string into the document
   super.insertString(offs, str, a);
   // lookup and select a matching item
   Object item = lookupItem(getText(0, getLength()));
   if (item != null) {
     setSelectedItem(item);
   } else {
     // keep old item selected if there is no match
     item = comboBox.getSelectedItem();
     // imitate no insert (later on offs will be incremented by str.length(): selection won't move
     // forward)
     offs = offs - str.length();
     // provide feedback to the user that his input has been received but can not be accepted
     comboBox
         .getToolkit()
         .beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
   }
   setText(item.toString());
   // select the completed part
   highlightCompletedText(offs + str.length());
 }
 /** Used to reset the contents of this document */
 public void clear() {
   try {
     super.remove(0, getLength());
     setMark();
   } catch (BadLocationException e) {
   }
 }
示例#4
0
    @Override
    public void insertString(final int offs, final String str, final AttributeSet a)
        throws BadLocationException {
      // NavigatorLogger.printMessage("Offset:"+offs+" STr:"+str+"L:"+getLength()+"attr:"+a);

      if ((getLength() + str.length()) <= maxLength) {
        final char[] source = str.toCharArray();
        final char[] result = new char[source.length];
        int j = 0;

        for (int i = 0; i < result.length; i++) {
          if (Character.isDigit(source[i])) {
            result[j++] = source[i];
          } else {
            toolkit.beep();
            if (log.isDebugEnabled()) {
              log.debug("insertString: " + source[i]); // NOI18N
            }
          }
        }
        super.insertString(offs, new String(result, 0, j), a);
        checked = false;
      } else {
        toolkit.beep();
      }
      if ((getLength()) == maxLength) { // getLength() ist schon aktualisiert
        if (bringFocus2Next == true) {
          checked = true;
          nextField.requestFocus();
        }
        // NavigatorLogger.printMessage("Sprung");
        // NavigatorLogger.printMessage(nextField);
      }
    }
  public static void setHexadecimalInputFilter(
      JTextComponent textComponent, int maximumInputLength) {
    PlainDocument plainDocument = (PlainDocument) textComponent.getDocument();
    plainDocument.setDocumentFilter(new HexadecimalInputFilter(maximumInputLength));

    String text = textComponent.getText();
    text = trimHexadecimal(text);

    if (text.length() > maximumInputLength) {
      textComponent.setText(text.substring(text.length() - maximumInputLength, text.length()));
    } else {
      while (text.length() < maximumInputLength) {
        text = "0" + text;
      }

      textComponent.setText(text);
    }
  }
示例#6
0
    public void insertString(int ii, String s, AttributeSet attributeset)
        throws BadLocationException {
      if (s == null || "".equals(s)) return;

      String base = getText(0, ii);
      String match = getMatch(base + s);

      if (match == null) {
        super.insertString(ii, s, attributeset);
        return;
      }

      int jj = ii + s.length();

      super.remove(0, getLength());
      super.insertString(0, base + s + match.substring(jj), attributeset);
      setSelectionStart(jj);
      setSelectionEnd(getLength());
    }
    // The insert string method
    public void insertString(int offs, String src, AttributeSet a) throws BadLocationException {

      char[] source = src.toCharArray();
      char[] result = new char[source.length];
      int j = 0;

      for (int i = 0; i < result.length; i++) {
        if (Character.isDigit(source[i])) result[j++] = source[i];
      }
      super.insertString(offs, new String(result, 0, j), a);
    }
  public void insertString(int offset, String s, AttributeSet attributeSet)
      throws BadLocationException {
    if ((limit == 0 || getLength() + s.length() <= limit) && Character.isDigit(s.charAt(0))) {
      // if we haven't reached the limit, insert the string
      super.insertString(offset, s, attributeSet);
    } else {
      // otherwise, just lose the string

      java.awt.Toolkit.getDefaultToolkit().beep();
    }
  }
示例#9
0
  /**
   * Alerts all listeners to this document of an insertion. This is overridden so we can update our
   * syntax highlighting stuff.
   *
   * <p>The syntax highlighting stuff has to be here instead of in <code>insertUpdate</code> because
   * <code>insertUpdate</code> is not called by the undo/redo actions, but this method is.
   *
   * @param e The change.
   */
  protected void fireInsertUpdate(DocumentEvent e) {

    /*
     * Now that the text is actually inserted into the content and
     * element structure, we can update our token elements and "last
     * tokens on lines" structure.
     */

    Element lineMap = getDefaultRootElement();
    DocumentEvent.ElementChange change = e.getChange(lineMap);
    Element[] added = change == null ? null : change.getChildrenAdded();

    int numLines = lineMap.getElementCount();
    int line = lineMap.getElementIndex(e.getOffset());
    int previousLine = line - 1;
    int previousTokenType = (previousLine > -1 ? lastTokensOnLines.get(previousLine) : Token.NULL);

    // If entire lines were added...
    if (added != null && added.length > 0) {

      Element[] removed = change.getChildrenRemoved();
      int numRemoved = removed != null ? removed.length : 0;

      int endBefore = line + added.length - numRemoved;
      // System.err.println("... adding lines: " + line + " - " + (endBefore-1));
      // System.err.println("... ... added: " + added.length + ", removed:" + numRemoved);
      for (int i = line; i < endBefore; i++) {

        setSharedSegment(i); // Loads line i's text into s.

        int tokenType = tokenMaker.getLastTokenTypeOnLine(s, previousTokenType);
        lastTokensOnLines.add(i, tokenType);
        // System.err.println("--------- lastTokensOnLines.size() == " +
        // lastTokensOnLines.getSize());

        previousTokenType = tokenType;
      } // End of for (int i=line; i<endBefore; i++).

      // Update last tokens for lines below until they stop changing.
      updateLastTokensBelow(endBefore, numLines, previousTokenType);

    } // End of if (added!=null && added.length>0).

    // Otherwise, text was inserted on a single line...
    else {

      // Update last tokens for lines below until they stop changing.
      updateLastTokensBelow(line, numLines, previousTokenType);
    } // End of else.

    // Let all listeners know about the insertion.
    super.fireInsertUpdate(e);
  }
示例#10
0
  /**
   * This method is called AFTER the content has been inserted into the document and the element
   * structure has been updated.
   *
   * <p>The syntax-highlighting updates need to be done here (as opposed to an override of <code>
   * postRemoveUpdate</code>) as this method is called in response to undo/redo events, whereas
   * <code>postRemoveUpdate</code> is not.
   *
   * <p>Now that the text is actually inserted into the content and element structure, we can update
   * our token elements and "last tokens on lines" structure.
   *
   * @param chng The change that occurred.
   * @see #removeUpdate
   */
  protected void fireRemoveUpdate(DocumentEvent chng) {

    Element lineMap = getDefaultRootElement();
    int numLines = lineMap.getElementCount();

    DocumentEvent.ElementChange change = chng.getChange(lineMap);
    Element[] removed = change == null ? null : change.getChildrenRemoved();

    // If entire lines were removed...
    if (removed != null && removed.length > 0) {

      int line = change.getIndex(); // First line entirely removed.
      int previousLine = line - 1; // Line before that.
      int previousTokenType =
          (previousLine > -1 ? lastTokensOnLines.get(previousLine) : Token.NULL);

      Element[] added = change.getChildrenAdded();
      int numAdded = added == null ? 0 : added.length;

      // Remove the cached last-token values for the removed lines.
      int endBefore = line + removed.length - numAdded;
      // System.err.println("... removing lines: " + line + " - " + (endBefore-1));
      // System.err.println("... added: " + numAdded + ", removed: " + removed.length);

      lastTokensOnLines.removeRange(
          line, endBefore); // Removing values for lines [line-(endBefore-1)].
      // System.err.println("--------- lastTokensOnLines.size() == " + lastTokensOnLines.getSize());

      // Update last tokens for lines below until they've stopped changing.
      updateLastTokensBelow(line, numLines, previousTokenType);

    } // End of if (removed!=null && removed.size()>0).

    // Otherwise, text was removed from just one line...
    else {

      int line = lineMap.getElementIndex(chng.getOffset());
      if (line >= lastTokensOnLines.getSize())
        return; // If we're editing the last line in a document...

      int previousLine = line - 1;
      int previousTokenType =
          (previousLine > -1 ? lastTokensOnLines.get(previousLine) : Token.NULL);
      // System.err.println("previousTokenType for line : " + previousLine + " is " +
      // previousTokenType);
      // Update last tokens for lines below until they've stopped changing.
      updateLastTokensBelow(line, numLines, previousTokenType);
    }

    // Let all of our listeners know about the removal.
    super.fireRemoveUpdate(chng);
  }
示例#11
0
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
      char[] source = str.toCharArray();
      char[] result = new char[source.length];
      int j = 0;

      for (int i = 0; i < result.length; i++) {
        if (Character.isDigit(source[i])) result[j++] = source[i];
        else {
          toolkit.beep();
          //			    System.err.println("insertString: " + source[i]);
        }
      }
      super.insertString(offs, new String(result, 0, j), a);
    }
 // This method is overriden from the super class. It will be called when
 // you are trying to insert text in your text component (by typing
 // or pasting).
 public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
   int currentLength = getLength();
   if (currentLength >= maxLength) {
     // There's not room for more characters. Return.
     return;
   }
   if (currentLength + str.length() > maxLength) {
     // All of the characters we are trying to insert will not fit.
     // We must trim the string.
     str = str.substring(0, maxLength - currentLength);
   }
   // Insert the text:
   super.insertString(offs, str, a);
 }
  @Override
  public void remove(int offs, int len) throws BadLocationException {
    int start = offs;
    int end = offs + len;

    int markStart = mark;
    int markEnd = getLength();

    if ((end < markStart) || (start > markEnd)) {
      // no overlap
      return;
    }

    // Determine interval intersection
    int cutStart = Math.max(start, markStart);
    int cutEnd = Math.min(end, markEnd);
    super.remove(cutStart, cutEnd - cutStart);
  }
  /**
   * Attempts to insert a string into the document. Produces a system beep if the input does not
   * represent a positive (or zero) integer.
   */
  public void insertString(int offset, String str, AttributeSet a) throws BadLocationException {
    StringBuffer intString;

    // Ignore zero-length and null strings
    if (str == null || str.length() == 0) return;

    intString = new StringBuffer(getText(0, getLength()));
    intString.insert(offset, str);

    try {
      int theInt = new Integer(intString.toString()).intValue();
      if (theInt < 0 || !allowZero && theInt == 0) {
        throw new NumberFormatException();
      }
      super.insertString(offset, str, a);
    } catch (NumberFormatException e) {
      Toolkit.getDefaultToolkit().beep();
    }
  }
示例#15
0
 public void remove(int offs, int len) throws BadLocationException {
   // return immediately when selecting an item
   if (selecting) {
     return;
   }
   if (hitBackspace) {
     // user hit backspace => move the selection backwards
     // old item keeps being selected
     if (offs > 0) {
       if (hitBackspaceOnSelection) {
         offs--;
       }
     } else {
       // User hit backspace with the cursor positioned on the start => beep
       comboBox.getToolkit().beep(); // when available use:
       // UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
     }
     highlightCompletedText(offs);
   } else {
     super.remove(offs, len);
   }
 }
 public void insertString(int offset, String str, AttributeSet attSet)
     throws BadLocationException {
   if (upperCase) str = str.toUpperCase();
   super.insertString(offset, str, attSet);
 }
 public void forceRemove(int offset, int len) throws BadLocationException {
   super.remove(offset, len);
 }
 public void forceInserting(int offset, String s, AttributeSet set) throws BadLocationException {
   super.insertString(offset, s, set);
 }
 @Override
 public void insertString(int offset, String text, AttributeSet a) throws BadLocationException {
   int len = getLength();
   super.insertString(len, text, a);
 }
示例#20
0
 public void replace(int i, int j, String s, AttributeSet attributeset)
     throws BadLocationException {
   super.remove(i, j);
   insertString(i, s, attributeset);
 }
示例#21
0
  /**
   * Inserts some content into the document. Inserting content causes a write lock to be held while
   * the actual changes are taking place, followed by notification to the observers on the thread
   * that grabbed the write lock.
   *
   * @param offset the starting offset >= 0
   * @param str the string to insert; does nothing with null/empty strings
   * @param attr the attributes for the inserted content
   */
  public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
    if (str == null) return;

    if ((getLength() + str.length()) <= limit) super.insertString(offset, str, attr);
  }
  @Override
  protected Document createDefaultModel() {
    PlainDocument d = (PlainDocument) super.createDefaultModel();

    d.setDocumentFilter(
        new DocumentFilter() {
          @Override
          public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
              throws BadLocationException {
            replace(fb, offset, 0, string, attr);
          }

          @Override
          public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
            replace(fb, offset, length, "", null);
          }

          @Override
          public void replace(
              FilterBypass fb, int replOffset, int replLen, String string, AttributeSet attrs)
              throws BadLocationException {
            String s = JMathTextField.this.getText();
            boolean insertedDummyChar = false;
            boolean insertedBrackets = false;
            String replStr = s.substring(replOffset, replOffset + replLen);

            if (string.matches(" |\\)")
                && replOffset + 1 <= s.length()
                && s.substring(replOffset, replOffset + 1).equals(string)) {
              JMathTextField.this.setCaretPosition(replOffset + 1);
              return;
            }

            if (string.isEmpty() && replStr.equals(" ")) {
              JMathTextField.this.setCaretPosition(replOffset);
              return;
            }

            string = string.replace(" ", "");
            if (string.isEmpty() && replStr.equals("(")) {
              int count = 1;
              while (replOffset + replLen < s.length()) {
                replLen++;
                replStr =
                    s.substring(
                        replOffset,
                        replOffset + replLen); // just update in case we need it later again
                if (replStr.charAt(0) == '(') count++;
                else if (replStr.charAt(0) == ')') count--;
                if (count == 0) break;
              }
            } else if (string.isEmpty() && replStr.equals(")")) {
              int count = -1;
              while (replOffset > 0) {
                replOffset--;
                replLen++;
                replStr = s.substring(replOffset, replOffset + replLen);
                if (replStr.charAt(0) == '(') count++;
                else if (replStr.charAt(0) == ')') count--;
                if (count == 0) break;
              }
            }

            if (string.matches("\\+|-|\\*|/|\\^|=")) {
              if (s.substring(replOffset + replLen).matches("( *(\\+|-|∙|/|\\^|=|\\)).*)|")) {
                string = string + "_";
                insertedDummyChar = true;
              } else if (s.substring(replOffset + replLen).matches(" .*")) {
                string = "_" + string;
                insertedDummyChar = true;
              }
            } else if (string.matches("\\(")) {
              if (Utils.reveresedString(s.substring(0, replOffset))
                      .matches("( )*([^\\+\\-∙/\\^= ].*|)")
                  || replStr.equals("_")) {
                string = "(_)";
                insertedDummyChar = true;
              } else if (!replStr.isEmpty()) {
                string = "(" + replStr + ")";
                insertedBrackets = true;
              } else return; // ignore this
            } else if (string.matches("\\)")) return; // ignore that

            // situation: A = B, press DEL -> make it A = _
            if (string.isEmpty()
                && Utils.reveresedString(s.substring(0, replOffset))
                    .matches("( )*(\\+|-|∙|/|\\^|=).*")
                && !replStr.matches("_|\\+|-|∙|/|\\^|=")) {
              string = "_";
              insertedDummyChar = true;
            } else if (string.isEmpty()
                && Utils.reveresedString(s.substring(0, replOffset))
                    .matches("( )*(\\+|-|∙|/|\\^|=).*")
                && replStr.equals("_")) {
              while (s.substring(replOffset - 1, replOffset).equals(" ")) {
                replOffset--;
                replLen++;
              }
              replOffset--;
              replLen++; // go just before the op
              // just update in case we need it later again
              // noinspection UnusedAssignment
              replStr = s.substring(replOffset, replOffset + replLen);
            }

            setNewString(
                fb, s.substring(0, replOffset) + string + s.substring(replOffset + replLen));

            if (insertedDummyChar) {
              int p = JMathTextField.this.getText().indexOf('_');
              if (p >= 0) {
                JMathTextField.this.setCaretPosition(p);
                JMathTextField.this.moveCaretPosition(p + 1);
              }
            } else if (insertedBrackets) {
              // move just before the ')'
              if (JMathTextField.this.getCaretPosition() > 0)
                JMathTextField.this.setCaretPosition(JMathTextField.this.getCaretPosition() - 1);
            }
          }

          synchronized void setNewString(FilterBypass fb, String tempStr)
              throws BadLocationException {
            operatorTree = OTParser.parse(tempStr, null);
            JMathTextField.this.updateByOpTree(fb);
          }
        });

    return d;
  }
示例#23
0
 @Override
 public void remove(final int offs, final int len) throws BadLocationException {
   checked = false;
   super.remove(offs, len);
 }