コード例 #1
0
 // TODO not used
 public void appendString(String str) {
   Document doc = getDocument();
   try {
     int start = doc.getLength();
     doc.insertString(doc.getLength(), str, null);
     int end = doc.getLength();
     // end = parseLine(start, end, patHistoryBtnStr);
   } catch (Exception e) {
     Debug.error(me + "appendString: Problem while trying to append\n%s", e.getMessage());
   }
 }
コード例 #2
0
ファイル: NumbrixGUI.java プロジェクト: rainerlg90/Numbrix
 private void updateBoard(DocumentEvent e) throws BadLocationException {
   Document doc = e.getDocument();
   int index = (int) doc.getProperty("index");
   String valueString = doc.getText(0, doc.getLength());
   if (doc.getLength() == 0) valueString = "0";
   int value = Integer.parseInt(valueString);
   gameBoard.changeCellAt(index, value);
   // gameBoard.out();
   if (gameBoard.checkGameOver()) {
     JOptionPane.showMessageDialog(frame, "NUMBRIX COMPLETED!!!");
   }
 }
コード例 #3
0
ファイル: Notepad.java プロジェクト: ArcherSys/ArcherSysRuby
    @Override
    @SuppressWarnings("SleepWhileHoldingLock")
    public void run() {
      try {
        // initialize the statusbar
        status.removeAll();
        JProgressBar progress = new JProgressBar();
        progress.setMinimum(0);
        progress.setMaximum(doc.getLength());
        status.add(progress);
        status.revalidate();

        // start writing
        Writer out = new FileWriter(f);
        Segment text = new Segment();
        text.setPartialReturn(true);
        int charsLeft = doc.getLength();
        int offset = 0;
        while (charsLeft > 0) {
          doc.getText(offset, Math.min(4096, charsLeft), text);
          out.write(text.array, text.offset, text.count);
          charsLeft -= text.count;
          offset += text.count;
          progress.setValue(offset);
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, e);
          }
        }
        out.flush();
        out.close();
      } catch (IOException e) {
        final String msg = e.getMessage();
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                JOptionPane.showMessageDialog(
                    getFrame(),
                    "Could not save file: " + msg,
                    "Error saving file",
                    JOptionPane.ERROR_MESSAGE);
              }
            });
      } catch (BadLocationException e) {
        System.err.println(e.getMessage());
      }
      // we are done... get rid of progressbar
      status.removeAll();
      status.revalidate();
    }
 /**
  * This function inserts or replaces the user's input in a string buffer, to create the text
  * which would be on screen if we allowed it. We declare to throw bad location due to
  * doc.getText, but since the paramters are coming from the farmework, that should never
  * happen.... in theory. If insert is true we insert, if false we replace. Length parameter only
  * used when replacing.
  */
 private StringBuffer getTextPrototype(
     boolean insert, FilterBypass fb, int offs, String str, int length)
     throws BadLocationException {
   Document doc = fb.getDocument();
   String text = doc.getText(0, doc.getLength());
   StringBuffer sb = new StringBuffer(text);
   if (insert) {
     sb.insert(offs, str);
   } else {
     sb.replace(offs, offs + length, str);
   }
   return sb;
 } // end of getTextPrototype
コード例 #5
0
  private static void insertQuestion(final JTextPane textPane, String str) {
    Document doc = textPane.getDocument();
    try {
      doc.insertString(doc.getLength(), str, null);

      final int pos = doc.getLength();
      System.out.println(pos);
      final JTextField field =
          new JTextField(4) {
            @Override
            public Dimension getMaximumSize() {
              return getPreferredSize();
            }
          };
      field.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
      field.addFocusListener(
          new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
              try {
                Rectangle rect = textPane.modelToView(pos);
                rect.grow(0, 4);
                rect.setSize(field.getSize());
                // System.out.println(rect);
                // System.out.println(field.getLocation());
                textPane.scrollRectToVisible(rect);
              } catch (BadLocationException ex) {
                ex.printStackTrace();
              }
            }

            @Override
            public void focusLost(FocusEvent e) {
              /* not needed */
            }
          });
      Dimension d = field.getPreferredSize();
      int baseline = field.getBaseline(d.width, d.height);
      field.setAlignmentY(baseline / (float) d.height);

      SimpleAttributeSet a = new SimpleAttributeSet();
      StyleConstants.setLineSpacing(a, 1.5f);
      textPane.setParagraphAttributes(a, true);

      textPane.insertComponent(field);
      doc.insertString(doc.getLength(), "\n", null);
    } catch (BadLocationException e) {
      e.printStackTrace();
    }
  }
コード例 #6
0
ファイル: FieldView.java プロジェクト: CodeingBoy/Java8CN
 /**
  * Determines the preferred span for this view along an axis.
  *
  * @param axis may be either View.X_AXIS or View.Y_AXIS
  * @return the span the view would like to be rendered into >= 0. Typically the view is told to
  *     render into the span that is returned, although there is no guarantee. The parent may
  *     choose to resize or break the view.
  */
 public float getPreferredSpan(int axis) {
   switch (axis) {
     case View.X_AXIS:
       Segment buff = SegmentCache.getSharedSegment();
       Document doc = getDocument();
       int width;
       try {
         FontMetrics fm = getFontMetrics();
         doc.getText(0, doc.getLength(), buff);
         width = Utilities.getTabbedTextWidth(buff, fm, 0, this, 0);
         if (buff.count > 0) {
           Component c = getContainer();
           firstLineOffset =
               sun.swing.SwingUtilities2.getLeftSideBearing(
                   (c instanceof JComponent) ? (JComponent) c : null, fm, buff.array[buff.offset]);
           firstLineOffset = Math.max(0, -firstLineOffset);
         } else {
           firstLineOffset = 0;
         }
       } catch (BadLocationException bl) {
         width = 0;
       }
       SegmentCache.releaseSharedSegment(buff);
       return width + firstLineOffset;
     default:
       return super.getPreferredSpan(axis);
   }
 }
コード例 #7
0
    public void execute() {
      if (!isEditable() || !isEnabled()) {
        return;
      }

      try {
        int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition();
        lastClickPoint = null;
        Document document = getDocument();
        String selectedText = getSelectedText();
        if (selectedText != null && !CommonUtil.isEmpty(selectedText)) {
          final int selectionEnd = getSelectionEnd();
          document.insertString(selectionEnd, selectedText, null);
          select(selectionEnd, selectionEnd + selectedText.length());
        } else {
          final int docLen = document.getLength();
          int fromIndex = Math.max(0, getText(0, position).lastIndexOf('\n'));
          int toIndex = getText(fromIndex + 1, docLen - fromIndex).indexOf('\n');
          toIndex = toIndex < 0 ? docLen : fromIndex + toIndex;
          String textToDuplicate = getText(fromIndex, toIndex - fromIndex + 1);
          if (!textToDuplicate.startsWith("\n")) {
            textToDuplicate = "\n" + textToDuplicate;
          }
          if (textToDuplicate.endsWith("\n")) {
            textToDuplicate = textToDuplicate.substring(0, textToDuplicate.length() - 1);
          }
          document.insertString(Math.min(docLen, toIndex + 1), textToDuplicate, null);
          setCaretPosition(position + textToDuplicate.length());
        }
      } catch (BadLocationException e1) {
        e1.printStackTrace();
      }
    }
コード例 #8
0
 private void addText(String str, String styleName, JTextPane pane) {
   Document doc = pane.getDocument();
   int len = doc.getLength();
   try {
     doc.insertString(len, str, pane.getStyle(styleName));
   } catch (javax.swing.text.BadLocationException e) {
   }
 }
    /**
     * Updates the shared value instance if updateValue is true. Always forces the redraw of
     * everything.
     */
    protected void doValueUpdate(FilterBypass fb) throws BadLocationException {
      Document doc = fb.getDocument();
      String text = doc.getText(0, doc.getLength());
      if (text.isEmpty()) {
        text = "0";
      }

      if (updateValue == true) {
        try {
          Double value = new Double(text);
          double newValue = multiplier.getValueToBeSet(value.doubleValue());
          cValue.setValue(newValue);
        } catch (NumberFormatException e) {
          // do nothing, since we allow '-'
        }
      }
      topContainer.forceRedraw();
    }
コード例 #10
0
 public void insertUpdate(DocumentEvent e) {
   Document doc = e.getDocument();
   try {
     prop.set(doc.getText(0, doc.getLength()));
   } catch (BadLocationException b) {
     // Once again, no idea what this is supposed to be.
     // I don't think I like this interface much :-(.
     System.out.println(b);
   }
 }
コード例 #11
0
    public void execute() {
      if (!isEditable() || !isEnabled()) {
        return;
      }
      int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition();
      lastClickPoint = null;
      Document document = getDocument();
      String selectedText = getSelectedText();

      try {
        if (selectedText != null && !CommonUtil.isEmpty(selectedText)) {
          String trimmed = selectedText.trim();
          if (trimmed.startsWith("<!--") && trimmed.endsWith("-->")) {
            StringBuffer buffer = new StringBuffer(selectedText);
            int pos = buffer.indexOf("<!--");
            buffer.delete(pos, pos + 4);
            pos = buffer.lastIndexOf("-->");
            buffer.delete(pos, pos + 3);
            replaceSelection(buffer.toString());
          } else {
            String newSelection = "<!--" + selectedText + "-->";
            replaceSelection(newSelection);
          }
        } else {
          final int docLen = document.getLength();
          int fromIndex = Math.max(0, getText(0, position).lastIndexOf('\n'));
          int toIndex = getText(fromIndex + 1, docLen - position).indexOf('\n');
          toIndex = toIndex < 0 ? docLen : fromIndex + toIndex;
          String textToComment = getText(fromIndex, toIndex - fromIndex + 1);

          if (textToComment.startsWith("\n")) {
            textToComment = textToComment.substring(1);
            fromIndex++;
          }
          if (textToComment.endsWith("\n")) {
            textToComment = textToComment.substring(0, textToComment.length() - 1);
            toIndex--;
          }
          String trimmed = textToComment.trim();
          if (trimmed.startsWith("<!--") && trimmed.endsWith("-->")) {
            int pos = textToComment.lastIndexOf("-->");
            document.remove(fromIndex + pos, 3);
            pos = textToComment.indexOf("<!--");
            document.remove(fromIndex + pos, 4);
          } else {
            document.insertString(Math.min(toIndex + 1, docLen), "-->", null);
            document.insertString(fromIndex, "<!--", null);
          }
        }
      } catch (BadLocationException e1) {
        e1.printStackTrace();
      }
    }
コード例 #12
0
 /*
  * public int search(String str){
  * return search(str, true);
  * }
  */
 public int search(String str, int pos, boolean forward) {
   boolean isCaseSensitive = true;
   String toSearch = str;
   if (str.startsWith("!")) {
     str = str.substring(1).toUpperCase();
     isCaseSensitive = false;
   }
   int ret = -1;
   Document doc = getDocument();
   Debug.log(9, "search caret: " + pos + ", " + doc.getLength());
   try {
     String body;
     int begin;
     if (forward) {
       int len = doc.getLength() - pos;
       body = doc.getText(pos, len > 0 ? len : 0);
       begin = pos;
     } else {
       body = doc.getText(0, pos);
       begin = 0;
     }
     if (!isCaseSensitive) {
       body = body.toUpperCase();
     }
     Pattern pattern = Pattern.compile(Pattern.quote(str));
     Matcher matcher = pattern.matcher(body);
     ret = continueSearch(matcher, begin, forward);
     if (ret < 0) {
       if (forward && pos != 0) {
         return search(toSearch, 0, forward);
       }
       if (!forward && pos != doc.getLength()) {
         return search(toSearch, doc.getLength(), forward);
       }
     }
   } catch (BadLocationException e) {
     Debug.log(7, "search caret: " + pos + ", " + doc.getLength() + e.getStackTrace());
   }
   return ret;
 }
コード例 #13
0
    public void actionPerformed(ActionEvent e) {
      JTextComponent textComponent = getTextComponent(e);
      if (!textComponent.isEditable() || !textComponent.isEnabled()) {
        return;
      }

      try {
        final int position = getCaretPosition();
        final Document document = getDocument();
        int docLen = document.getLength();

        if (docLen == 0) {
          return;
        }

        int fromIndex = Math.max(0, getText(0, position).lastIndexOf('\n'));
        int toIndex = getText(fromIndex + 1, docLen - fromIndex - 1).indexOf('\n');
        toIndex = toIndex < 0 ? docLen : fromIndex + toIndex + 1;
        String text = getText(fromIndex, toIndex - fromIndex);
        if (text.startsWith("\n") || toIndex >= docLen) {
          document.remove(fromIndex, toIndex - fromIndex);
        } else {
          document.remove(fromIndex, toIndex - fromIndex + 1);
        }

        int newPosition = 0;
        if (fromIndex > 0) {
          newPosition = fromIndex + 1;
        }
        docLen = document.getLength();
        if (newPosition > docLen) {
          newPosition = getText().lastIndexOf('\n') + 1;
        }
        setCaretPosition(newPosition);
      } catch (BadLocationException e1) {
        e1.printStackTrace();
      }
    }
 void updateTheLabel(DocumentEvent e) {
   Document doc = (Document) e.getDocument();
   String text = null;
   try {
     text = doc.getText(0, doc.getLength());
     doc = null;
   } catch (BadLocationException ex) {
     text = null;
   }
   if (text != null) {
     try {
       double number = Double.parseDouble(text);
       if (number > 1) {
         label.setText(labelPair.getPlural());
       } else {
         label.setText(labelPair.getSingular());
       }
     } catch (NumberFormatException ex) {
       // Do nothing
     } finally {
       text = null;
     }
   }
 }
コード例 #15
0
  @Override
  public void insertString(
      FilterBypass filterBypass, int offset, String text, AttributeSet attributeSet)
      throws BadLocationException {
    text = trimHexadecimal(text);
    Document document = filterBypass.getDocument();
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(document.getText(0, document.getLength()));
    stringBuilder.insert(offset, text);

    if (isValidInput(stringBuilder.toString(), 0)) {
      super.insertString(filterBypass, offset, text, attributeSet);
    } else {
      Toolkit.getDefaultToolkit().beep();
    }
  }
コード例 #16
0
  private void applyFontSize() {
    Document document = myEditorPane.getDocument();
    if (!(document instanceof StyledDocument)) {
      return;
    }

    StyledDocument styledDocument = (StyledDocument) document;
    if (myFontSizeStyle == null) {
      myFontSizeStyle = styledDocument.addStyle("active", null);
    }

    EditorColorsManager colorsManager = EditorColorsManager.getInstance();
    EditorColorsScheme scheme = colorsManager.getGlobalScheme();
    StyleConstants.setFontSize(myFontSizeStyle, scheme.getQuickDocFontSize().getSize());
    if (Registry.is("documentation.component.editor.font")) {
      StyleConstants.setFontFamily(myFontSizeStyle, scheme.getEditorFontName());
    }
    styledDocument.setCharacterAttributes(0, document.getLength(), myFontSizeStyle, false);
  }
コード例 #17
0
ファイル: NumbrixGUI.java プロジェクト: rainerlg90/Numbrix
    @Override
    public void replace(
        DocumentFilter.FilterBypass fp, int offset, int length, String string, AttributeSet aset)
        throws BadLocationException {
      Document doc = fp.getDocument();
      String oldText = doc.getText(0, doc.getLength());
      StringBuilder sb = new StringBuilder(oldText);
      sb.replace(offset, offset + length, oldText);

      int len = string.length();
      boolean isValidInteger = true;

      for (int i = 0; i < len; i++) {
        if (!Character.isDigit(string.charAt(i))) {
          isValidInteger = false;
          break;
        }
      }
      if (isValidInteger && verifyText(sb.toString())) {
        super.replace(fp, offset, length, string, aset);
      } else Toolkit.getDefaultToolkit().beep();
    }