Java Code Examples for javax.swing.text.BadLocationException#offsetRequested()

The following examples show how to use javax.swing.text.BadLocationException#offsetRequested() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
private static void setDummyText(JTextPane textPane, MutableAttributeSet attr) {
  textPane.setText("12341234\n1234 567890 5555 66666 77777\n88 999999 ");
  try {
    StyledDocument doc = textPane.getStyledDocument();
    doc.insertString(doc.getLength(), "134500698\n", attr);
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
  // StyledDocument doc = new DefaultStyledDocument();
  // MutableAttributeSet a = new SimpleAttributeSet();
  // StyleConstants.setLineSpacing(a, .5f);
  // doc.setParagraphAttributes(0, doc.getLength() - 1, a, false);
  // textPane.setStyledDocument(doc);
}
 
Example 2
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
@Override protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) {
  super.paintTrack(g, c, trackBounds);

  Rectangle rect = textArea.getBounds();
  double sy = trackBounds.getHeight() / rect.getHeight();
  AffineTransform at = AffineTransform.getScaleInstance(1d, sy);
  Highlighter highlighter = textArea.getHighlighter();
  g.setColor(Color.YELLOW);
  try {
    for (Highlighter.Highlight hh: highlighter.getHighlights()) {
      Rectangle r = textArea.modelToView(hh.getStartOffset());
      Rectangle s = at.createTransformedShape(r).getBounds();
      int h = 2; // Math.max(2, s.height - 2);
      g.fillRect(trackBounds.x, trackBounds.y + s.y, trackBounds.width, h);
    }
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
}
 
Example 3
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
@Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
  String txt = Objects.toString(value, "");
  getHighlighter().removeAllHighlights();
  setText(txt);
  setBackground(selected ? BACKGROUND_SELECTION_COLOR : Color.WHITE);
  if (query != null && !query.isEmpty() && txt.startsWith(query)) {
    try {
      getHighlighter().addHighlight(0, query.length(), HIGHLIGHT);
    } catch (BadLocationException ex) {
      // should never happen
      RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
      wrap.initCause(ex);
      throw wrap;
    }
  }
  return this;
}
 
Example 4
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
public static int getFirstLineCenterY(String text, AbstractButton c, Rectangle iconRect) {
  int y = 0;
  if (Objects.nonNull(text) && c.getVerticalTextPosition() == SwingConstants.TOP) {
    View v = (View) c.getClientProperty(BasicHTML.propertyKey);
    if (Objects.nonNull(v)) {
      try {
        Element e = v.getElement().getElement(0);
        Shape s = new Rectangle();
        Position.Bias b = Position.Bias.Forward;
        s = v.modelToView(e.getStartOffset(), b, e.getEndOffset(), b, s);
        // System.out.println("v.h: " + s.getBounds());
        y = Math.round(Math.abs(s.getBounds().height - iconRect.height) / 2f);
      } catch (BadLocationException ex) {
        // should never happen
        RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
        wrap.initCause(ex);
        throw wrap;
      }
    }
  }
  return y;
}
 
Example 5
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
private void append(String str) {
  Document doc = jtp.getDocument();
  String text;
  if (doc.getLength() > LIMIT) {
    timerStop();
    startButton.setEnabled(false);
    text = "doc.getLength()>1000";
  } else {
    text = str;
  }
  try {
    doc.insertString(doc.getLength(), text + LS, null);
    jtp.setCaretPosition(doc.getLength());
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
}
 
Example 6
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
private void paintCustomParagraph(Graphics g, Shape a) {
  try {
    Shape paragraph = modelToView(getEndOffset(), a, Position.Bias.Backward);
    Rectangle r = Objects.nonNull(paragraph) ? paragraph.getBounds() : a.getBounds();
    int x = r.x;
    int y = r.y;
    int h = r.height;
    // paragraphMarkIcon.paintIcon(null, g, x, y);
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setPaint(MARK_COLOR);
    g2.drawLine(x + 1, y + h / 2, x + 1, y + h - 4);
    g2.drawLine(x + 2, y + h / 2, x + 2, y + h - 5);
    g2.drawLine(x + 3, y + h - 6, x + 3, y + h - 6);
    g2.dispose();
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
}
 
Example 7
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
private void paintCustomParagraph(Graphics g, Shape a) {
  try {
    Shape paragraph = modelToView(getEndOffset(), a, Position.Bias.Backward);
    Rectangle r = Objects.nonNull(paragraph) ? paragraph.getBounds() : a.getBounds();
    int x = r.x;
    int y = r.y;
    int h = r.height;
    Color old = g.getColor();
    g.setColor(MARK_COLOR);
    g.drawLine(x + 1, y + h / 2, x + 1, y + h - 4);
    g.drawLine(x + 2, y + h / 2, x + 2, y + h - 5);
    g.drawLine(x + 3, y + h - 6, x + 3, y + h - 6);
    g.setColor(old);
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
}
 
Example 8
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
@Override public void setText(String str) {
  super.setText(str);
  FontMetrics fm = getFontMetrics(getFont());
  Document doc = getDocument();
  Element root = doc.getDefaultRootElement();
  int lineCount = root.getElementCount(); // = root.getElementIndex(doc.getLength());
  int maxWidth = 10;
  try {
    for (int i = 0; i < lineCount; i++) {
      Element e = root.getElement(i);
      int rangeStart = e.getStartOffset();
      int rangeEnd = e.getEndOffset();
      String line = doc.getText(rangeStart, rangeEnd - rangeStart);
      int width = fm.stringWidth(line);
      if (maxWidth < width) {
        maxWidth = width;
      }
    }
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
  setRows(lineCount);
  setColumns(1 + maxWidth / getColumnWidth());
}
 
Example 9
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
@Override public void paint(Graphics g, Shape allocation) {
  super.paint(g, allocation);
  try {
    Shape para = modelToView(getEndOffset(), allocation, Bias.Backward);
    Rectangle r = Objects.nonNull(para) ? para.getBounds() : allocation.getBounds();
    PARAGRAPH_MARK.paintIcon(null, g, r.x, r.y);
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
}
 
Example 10
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
protected void addHighlight(Element element, boolean isBlock) {
  Highlighter highlighter = editorPane.getHighlighter();
  int start = element.getStartOffset();
  int lf = isBlock ? 1 : 0;
  int end = element.getEndOffset() - lf; // lf???, setDrawsLayeredHighlights(false) bug???
  try {
    highlighter.addHighlight(start, end, HIGHLIGHT);
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
}
 
Example 11
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
protected void append(Message m) {
  StyledDocument doc = jtp.getStyledDocument();
  try {
    doc.insertString(doc.getLength(), m.text + "\n", doc.getStyle(m.type.toString()));
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
}
 
Example 12
Source File: DocumentUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public synchronized char charAt(int index) {
    try {
        doc.getText(index, 1, segment);
    } catch (BadLocationException e) {
        IndexOutOfBoundsException ioobe = new IndexOutOfBoundsException(e.getMessage()
            + " at offset=" + e.offsetRequested()); // NOI18N
        ioobe.initCause(e);
        throw ioobe;
    }
    char ch = segment.array[segment.offset];
    segment.array = null; // Allow GC of large char arrays
    return ch;
}
 
Example 13
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private static void removeLines(Document doc, Element root) {
  Element fl = root.getElement(0);
  try {
    doc.remove(0, fl.getEndOffset());
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
}
 
Example 14
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
public static void append(JTextComponent editor, String str) {
  try {
    Document doc = editor.getDocument();
    doc.insertString(editor.getCaretPosition(), str, null);
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
}
 
Example 15
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private void append(String str, boolean flg) {
  String style = flg ? StyleContext.DEFAULT_STYLE : "error";
  StyledDocument doc = jtp.getStyledDocument();
  try {
    doc.insertString(doc.getLength(), str + "\n", doc.getStyle(style));
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
}
 
Example 16
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
@Override public void paint(Graphics g) {
  if (isVisible()) {
    try {
      JTextComponent component = getComponent();
      TextUI mapper = component.getUI();
      Rectangle r = mapper.modelToView(component, getDot());
      g.setColor(component.getCaretColor());
      int width = g.getFontMetrics().charWidth('w');
      // A patch for full width characters >>>>
      if (isOvertypeMode()) {
        int pos = getCaretPosition();
        if (pos < getDocument().getLength()) {
          if (getSelectionStart() == getSelectionEnd()) {
            String str = getText(pos, 1);
            width = g.getFontMetrics().stringWidth(str);
          } else {
            width = 0;
          }
        }
      } // <<<<
      int y = r.y + r.height - 2;
      g.drawLine(r.x, y, r.x + width - 2, y);
    } catch (BadLocationException ex) {
      // should never happen
      RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
      wrap.initCause(ex);
      throw wrap;
    }
  }
}
 
Example 17
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
public void textProgress(boolean append) {
  if (append) {
    area.append("*");
  } else {
    try {
      Document doc = area.getDocument();
      doc.remove(doc.getLength() - 1, 1);
    } catch (BadLocationException ex) {
      // should never happen
      RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
      wrap.initCause(ex);
      throw wrap;
    }
  }
}
 
Example 18
Source File: MainPanel.java    From java-swing-tips with MIT License 4 votes vote down vote up
private MainPanel() {
  super(new GridLayout(2, 1));
  String str = "red green blue 111111111111111111111111111111111";

  JTextPane textPane = new JTextPane() {
    @Override public void scrollRectToVisible(Rectangle rect) {
      rect.grow(getInsets().right, 0);
      super.scrollRectToVisible(rect);
    }
  };

  // @see https://ateraimemo.com/Swing/NoWrapTextPane.html
  textPane.setEditorKit(new NoWrapEditorKit());

  AbstractDocument doc = new SimpleSyntaxDocument();
  textPane.setDocument(doc);
  try {
    doc.insertString(0, str, null);
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
  String key = "Do-Nothing";
  InputMap im = textPane.getInputMap(JComponent.WHEN_FOCUSED);
  im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), key);
  im.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), key);
  textPane.getActionMap().put(key, new AbstractAction() {
    @Override public void actionPerformed(ActionEvent e) {
      // Do nothing
    }
  });

  // @see https://ateraimemo.com/Swing/FocusTraversalKeys.html
  int ftk = KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS;
  Set<AWTKeyStroke> forwardKeys = new HashSet<>(textPane.getFocusTraversalKeys(ftk));
  forwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
  forwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_DOWN_MASK));
  textPane.setFocusTraversalKeys(ftk, forwardKeys);

  // // @see https://tips4java.wordpress.com/2009/01/25/no-wrap-text-pane/
  // textPane.addCaretListener(new VisibleCaretListener());

  JScrollPane scrollPane = new JScrollPane(textPane) {
    @Override public void updateUI() {
      super.updateUI();
      setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
      setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
      setBorder(BorderFactory.createLineBorder(Color.GRAY));
      setViewportBorder(BorderFactory.createEmptyBorder());
    }

    @Override public Dimension getMinimumSize() {
      return super.getPreferredSize();
    }
  };

  add(makeTitledPanel("JTextField", new JTextField(str)));
  add(makeTitledPanel("JTextPane+StyledDocument+JScrollPane", scrollPane));
  setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
  setPreferredSize(new Dimension(320, 240));
}
 
Example 19
Source File: MainPanel.java    From java-swing-tips with MIT License 4 votes vote down vote up
private static JEditorPane makeEditorPane(boolean editable) {
  JEditorPane editorPane = new JEditorPane();
  editorPane.setEditable(editable);
  editorPane.setContentType("text/html");
  editorPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
  editorPane.setText(HTML_TEXT);
  editorPane.addHyperlinkListener(e -> {
    if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
      JOptionPane.showMessageDialog(editorPane, "You click the link with the URL " + e.getURL());
    } else if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) {
      tooltip = editorPane.getToolTipText();
      URL url = e.getURL();
      editorPane.setToolTipText(Objects.nonNull(url) ? url.toExternalForm() : null);
    } else if (e.getEventType() == HyperlinkEvent.EventType.EXITED) {
      editorPane.setToolTipText(tooltip);
    }
  });

  HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
  Style s = doc.addStyle("button", null);
  StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
  HyperlinkButton button = new HyperlinkButton(LINK);
  button.addActionListener(e -> {
    AbstractButton b = (AbstractButton) e.getSource();
    editorPane.setBackground(b.isSelected() ? Color.RED : Color.WHITE);
    JOptionPane.showMessageDialog(editorPane, "You click the link with the URL " + LINK);
  });
  button.setToolTipText("button: " + LINK);
  button.setOpaque(false);
  StyleConstants.setComponent(s, button);
  try {
    doc.insertString(doc.getLength(), "\n----\nJButton:\n", null);
    doc.insertString(doc.getLength(), LINK + "\n", doc.getStyle("button"));
    // doc.insertString(doc.getLength(), "\n", null);
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
  return editorPane;
}
 
Example 20
Source File: MainPanel.java    From java-swing-tips with MIT License 4 votes vote down vote up
private MainPanel() {
  super(new BorderLayout());
  String[] columnNames = {"String", "Integer", "Boolean"};
  Object[][] data = {
    {"aaa", 12, true}, {"zzz", 6, false}, {"bbb", 22, true}, {"nnn", 9, false},
    {"ccc", 32, true}, {"ooo", 8, false}, {"ddd", 42, true}, {"ppp", 9, false},
    {"eee", 52, true}, {"qqq", 8, false}, {"fff", 62, true}, {"rrr", 7, false},
    {"ggg", 51, true}, {"sss", 6, false}, {"hhh", 41, true}, {"ttt", 5, false},
    {"iii", 51, true}, {"uuu", 4, false}, {"jjj", 61, true}, {"vvv", 3, false},
    {"kkk", 72, true}, {"www", 2, false}, {"lll", 82, true}, {"xxx", 1, false},
    {"mmm", 92, true}, {"yyy", 0, false}
  };
  DefaultTableModel model = new DefaultTableModel(data, columnNames) {
    @Override public Class<?> getColumnClass(int column) {
      return getValueAt(0, column).getClass();
    }
  };
  JTable table = new JTable(model);
  table.setAutoCreateRowSorter(true);

  JTextPane textPane = new JTextPane();
  textPane.setEditable(false);
  textPane.setMargin(new Insets(5, 10, 5, 5));

  JTextComponent c = new JTextArea(TEXT);
  c.setEditable(false);

  Document doc = textPane.getDocument();
  try {
    doc.insertString(doc.getLength(), TEXT, null);
    doc.insertString(doc.getLength(), TEXT, null);
    doc.insertString(doc.getLength(), TEXT, null);
    textPane.insertComponent(createChildScrollPane(c));
    doc.insertString(doc.getLength(), "\n", null);
    doc.insertString(doc.getLength(), TEXT, null);
    textPane.insertComponent(createChildScrollPane(table));
    doc.insertString(doc.getLength(), "\n", null);
    doc.insertString(doc.getLength(), TEXT, null);
    textPane.insertComponent(new JScrollPane(new JTree()));
    doc.insertString(doc.getLength(), "\n", null);
    doc.insertString(doc.getLength(), TEXT, null);
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
  add(new JLayer<>(new JScrollPane(textPane), new WheelScrollLayerUI()));
  // add(new JScrollPane(textPane));
  setPreferredSize(new Dimension(320, 240));
}