/** * This method initializes jTextPane * * @return javax.swing.JTextPane */ private JTextPane getJTextPane() { if (jTextPane == null) { jTextPane = new JTextPane(); jTextPane.setEditorKit(new HTMLEditorKit()); HTMLDocument doc = new HTMLDocument() { private static final long serialVersionUID = 1L; @Override public Font getFont(AttributeSet attr) { Object family = attr.getAttribute(StyleConstants.FontFamily); Object size = attr.getAttribute(StyleConstants.FontSize); if (family == null && size == null) { return new Font("SansSerif", Font.PLAIN, currentFontSize); } return super.getFont(attr); } }; doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE); doc.setPreservesUnknownTags(false); jTextPane.setStyledDocument(doc); jTextPane.setEditable(false); } return jTextPane; }
private final void find(Pattern pattern) { final WriteOnce<Integer> once = new WriteOnce<Integer>(); final Highlighter highlighter = textPane.getHighlighter(); highlighter.removeAllHighlights(); int matches = 0; final HTMLDocument doc = (HTMLDocument) textPane.getDocument(); for (final HTMLDocument.Iterator it = doc.getIterator(HTML.Tag.CONTENT); it.isValid(); it.next()) try { final String fragment = doc.getText(it.getStartOffset(), it.getEndOffset() - it.getStartOffset()); final Matcher matcher = pattern.matcher(fragment); while (matcher.find()) { highlighter.addHighlight( it.getStartOffset() + matcher.start(), it.getStartOffset() + matcher.end(), HIGHLIGHTER); once.set(it.getStartOffset()); ++matches; } } catch (final BadLocationException ex) { } if (!once.isEmpty()) textPane.setCaretPosition(once.get()); this.matches.setText(String.format("%d matches", matches)); }
public void resetDocument() { if (document != null) document.removeUndoableEditListener(view.getUndoListener()); HTMLEditorKit htmlEditorKit = new HTMLEditorKit(); document = (HTMLDocument) htmlEditorKit.createDefaultDocument(); document.addUndoableEditListener(view.getUndoListener()); view.update(); }
public JSONArray convertHTMLToFlag(HTMLDocument htmlDoc) { boolean isExistFace = false; ElementIterator it = new ElementIterator(htmlDoc); Element element; while ((element = it.next()) != null) { if (element.getName().equals(HTML.Tag.IMG.toString())) { isExistFace = true; try { String name = element.getAttributes().getAttribute(HTML.Attribute.NAME).toString(); // String src = element.getAttributes().getAttribute(HTML.Attribute.SRC).toString(); int offset = element.getStartOffset(); htmlDoc.replace(offset, element.getEndOffset() - offset, "~face:" + name + "~", null); } catch (BadLocationException ex) { Logger.getLogger(QQImageUtil.class.getName()).log(Level.SEVERE, null, ex); } } } String text = null; try { text = htmlDoc.getText(0, htmlDoc.getLength()); htmlDoc.remove(0, htmlDoc.getLength()); } catch (BadLocationException ex) { Logger.getLogger(QQImageUtil.class.getName()).log(Level.SEVERE, null, ex); } if (isExistFace) { text = text.replaceFirst("\\n", ""); } // Log.println(text); JSONArray msg = new JSONArray(); String[] arr = text.split("~"); for (int i = 0; i < arr.length; i++) { String temp = arr[i]; // Log.println(temp); if (temp.startsWith("face:")) { String[] tempArray = temp.split(":"); JSONArray face = new JSONArray(); face.add(tempArray[0]); String regex = ",([0-9]*):" + tempArray[1] + ","; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(faceFlag); String result = null; if (m.find()) { result = m.group(1); } else { result = tempArray[1]; } int faceNumber = Integer.parseInt(result); face.add(faceNumber); msg.add(face); } else { msg.add(temp); } } // Log.println(msg); return msg; }
private void addHTML(String text) { HTMLDocument hdoc = (HTMLDocument) doc; try { hdoc.insertAfterEnd(hdoc.getCharacterElement(hdoc.getLength()), text); } catch (BadLocationException | IOException ex) { ex.printStackTrace(); } }
private void appendMsg(String msg) { HTMLDocument doc = (HTMLDocument) textArea.getDocument(); HTMLEditorKit kit = (HTMLEditorKit) textArea.getEditorKit(); try { kit.insertHTML(doc, doc.getLength(), msg, 0, 0, null); } catch (Exception e) { Debug.error(me + "Problem appending text to message area!\n%s", e.getMessage()); } }
public void initImageLoader(HTMLDocument document) { try { document.setBase(new URL(ImageLoaderCache.IMAGE_URL_PREFIX)); } catch (MalformedURLException e) { log.error(e.getMessage()); } setContextResource(navigator.getCurrentResource()); document.getDocumentProperties().put("imageCache", this); }
/** * Creates component. * * @param collection collection to show. * @param treeMode <code>TRUE</code> to set tree mode by default. * @param readingLists <code>TRUE</code> if showing reading lists. */ public CListTree(Collection collection, boolean treeMode, boolean readingLists) { this.collection = collection; this.readingLists = readingLists; itemListener = new CItemListener(); setLayout(new BorderLayout()); setTreeMode(treeMode); BBFormBuilder builder = new BBFormBuilder("p, 2dlu, p, 0:grow"); JComboBox cbViewMode = new JComboBox( new Object[] { Strings.message("collections.viewmode.tree"), Strings.message("collections.viewmode.list") }); cbViewMode.setSelectedIndex(treeMode ? 0 : 1); cbViewMode.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent e) { JComboBox box = (JComboBox) e.getSource(); boolean isTree = box.getSelectedIndex() == 0; setTreeMode(isTree); } }); builder.append(Strings.message("collections.viewmode"), cbViewMode); builder.appendRelatedComponentsGapRow(2); add(builder.getPanel(), BorderLayout.NORTH); // Description area taDescription = new JEditorPane(); Color back = taDescription.getBackground(); taDescription.setEditable(false); taDescription.setBackground(back); taDescription.setEditorKit(new CustomHTMLEditorKit()); HTMLDocument doc = (HTMLDocument) taDescription.getDocument(); Style def = doc.getStyle("default"); Font font = UIManager.getFont("TextArea.font"); if (SystemUtils.IS_OS_MAC) font = UifUtilities.applyFontBias(font, -2); UifUtilities.setFontAttributes(doc.addStyle(TEXT_STYLE, def), font); builder = new BBFormBuilder("0:grow"); builder.appendUnrelatedComponentsGapRow(2); builder.appendRow("p"); builder.append(Strings.message("collections.description"), 1); builder.appendRelatedComponentsGapRow(2); builder.appendRow("50px"); builder.append(taDescription, 1, CellConstraints.FILL, CellConstraints.FILL); add(builder.getPanel(), BorderLayout.SOUTH); }
public void appendToEnd(String text) { Element root = document.getDefaultRootElement(); try { document.insertAfterEnd(root.getElement(root.getElementCount() - 1), text); } catch (BadLocationException e) { logger.error("Insert in the HTMLDocument failed.", e); } catch (IOException e) { logger.error("Insert in the HTMLDocument failed.", e); } }
/** * Extracts text from an HTML document and stores it in the document. * * @param filesInputStream An input stream pointing to the HTML document to be read. * @throws BadLocationException * @throws IOException */ private static char[] loadHTML(InputStream filesInputStream) throws IOException, BadLocationException { EditorKit kit = new HTMLEditorKit(); HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument(); doc.putProperty("IgnoreCharsetDirective", true); kit.read(filesInputStream, doc, 0); char[] origText = doc.getText(0, doc.getLength()).toCharArray(); return origText; }
private void replaceRange(String newStr, int start, int end) { HTMLDocument doc = (HTMLDocument) getDocument(); try { doc.remove(start, (end - start)); insert(newStr, start); } catch (BadLocationException ble) { ble.printStackTrace(); } setDocument(doc); }
public void hyperlinkUpdate(HyperlinkEvent event) { HTMLDocument documentHTML = null; if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { m_sPageCourante = event.getURL().toString(); if (event instanceof HTMLFrameHyperlinkEvent) { documentHTML = (HTMLDocument) jEditorPaneHTML.getDocument(); documentHTML.processHTMLFrameHyperlinkEvent((HTMLFrameHyperlinkEvent) event); } else ChargerPageActive(); } }
public void ClearLog() { try { doc.replace(0, doc.getLength(), "", null); kit.insertHTML(doc, 0, "", 0, 0, null); } catch (BadLocationException e) { // TODO Auto-generated catch block // e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); } }
// appends a message to the log tab and system out. public void Log(String msg) { try { kit.insertHTML(doc, doc.getLength(), msg, 0, 0, null); int over_length = doc.getLength() - msg.length() - 5000; doc.remove(0, over_length); } catch (BadLocationException e) { // TODO Auto-generated catch block // e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); } }
private static void appendHTML(JEditorPane editor, String html) { try { html = StringUtil.replaceAll(html, "\t", " "); html = StringUtil.replaceAll(html, "\r\n", "\n"); html = StringUtil.replaceAll(html, "\r", ""); Vector vt = StringUtil.toStringVector(html, "\n"); HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit(); HTMLDocument doc = (HTMLDocument) editor.getDocument(); for (int iIndex = 0; iIndex < vt.size(); iIndex++) kit.insertHTML(doc, doc.getLength(), (String) vt.elementAt(iIndex), 0, 0, null); } catch (Exception e) { e.printStackTrace(); } }
public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { JEditorPane pane = (JEditorPane) e.getSource(); if (e instanceof HTMLFrameHyperlinkEvent) { HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e; HTMLDocument doc = (HTMLDocument) pane.getDocument(); doc.processHTMLFrameHyperlinkEvent(evt); } else { String url = e.getURL().toString(); Loader loader = LoaderFactory.getInstance().newLoader(); loader.download(url, new Target(Library.PRIMARY_FRAME, null)); } } }
public void ecrire(String s) { JScrollBar scroll = jScrollPane1.getVerticalScrollBar(); scrollMax = scroll.getMaximum(); scrollVisible = scroll.isShowing(); if (scroll.getValue() + scroll.getVisibleAmount() == scrollMax) { // enBas = false; scrollAuto = true; // scrollMax = scroll.getMaximum(); } else { enBas = false; scrollAuto = false; } HTMLDocument d = (HTMLDocument) afficheurHTML.getStyledDocument(); Element a = d.getParagraphElement(1); // Element a=d.getElement("conversation"); try { if (!vide) { d.insertBeforeEnd(a, "<br />" + s); } else { d.insertBeforeEnd(a, s); vide = false; } } catch (BadLocationException | IOException ex) { Logger.getLogger(FenetreJeu.class.getName()).log(Level.SEVERE, null, ex); } /* * if (enBas) { while (scroll.getMaximum() == scrollMax) { try { * Thread.sleep(5); * * * } catch (InterruptedException ex) { * Logger.getLogger(FenetreJeu.class.getName()).log(Level.SEVERE, null, * ex); } } scroll.setValue(scroll.getMaximum() - * scroll.getVisibleAmount()); } */ /* * if (jScrollPane1.getVerticalScrollBar().getValue() == * jScrollPane1.getVerticalScrollBar().getMaximum()) { * afficheurHTML.setCaretPosition(afficheurHTML.getDocument().getLength()); * } */ // System.out.println(afficheurHTML.getText()); // System.out.println(jScrollPane1.getVerticalScrollBar().getMaximum()); }
public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { if (e instanceof HTMLFrameHyperlinkEvent) { HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e; HTMLDocument doc = (HTMLDocument) this.getDocument(); doc.processHTMLFrameHyperlinkEvent(evt); } else { try { URL url = e.getURL(); if (url != null) this.setPage(url); } catch (Throwable t) { t.printStackTrace(); } } } }
public void toChatScreen(String toScreen, boolean selfSeen) throws IOException, BadLocationException { // Timestamp ts = new Timestamp(); String toScreenFinal = ""; Date now = Calendar.getInstance().getTime(); SimpleDateFormat format = new SimpleDateFormat("hh:mm"); String ts = format.format(now); // chatScreen.append(ts + " " + toScreen + "\n"); toScreenFinal = "<font color=gray>" + ts + "</font> "; if (selfSeen) toScreenFinal = toScreenFinal + "<font color=red>" + toScreen + "</font>"; else toScreenFinal = toScreenFinal + toScreen; // chatter.addTo(toScreen); // if(standardWindow) { // chatScreen.setCaretPosition(chatScreen.getDocument().getLength()); // } // else { JScrollBar vBar = scrollChat.getVerticalScrollBar(); int vSize = vBar.getVisibleAmount(); int maxVBar = vBar.getMaximum(); int currVBar = vBar.getValue() + vSize; kit.insertHTML(doc, doc.getLength(), toScreenFinal, 0, 0, null); if (maxVBar == currVBar) { chatScreen.setCaretPosition(chatScreen.getDocument().getLength()); } // } // kit.insertHTML(doc, doc.getLength(), toScreenFinal, 0, 0, null); }
@Override public void writeSource(String x) { try { htmlKit.insertHTML(htmlDoc, htmlDoc.getLength(), x, 0, 0, null); } catch (Exception e) { e.printStackTrace(); } }
/** * Tweaks a <code>JEditorPane</code> so it can be used to render the content in a focusable * pseudo-tool tip. It is assumed that the editor pane is using an <code>HTMLDocument</code>. * * @param textArea The editor pane to tweak. */ public static void tweakTipEditorPane(JEditorPane textArea) { // Jump through a few hoops to get things looking nice in Nimbus boolean isNimbus = isNimbusLookAndFeel(); if (isNimbus) { Color selBG = textArea.getSelectionColor(); Color selFG = textArea.getSelectedTextColor(); textArea.setUI(new javax.swing.plaf.basic.BasicEditorPaneUI()); textArea.setSelectedTextColor(selFG); textArea.setSelectionColor(selBG); } textArea.setEditable(false); // Required for links to work! textArea.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); // Make selection visible even though we are not (initially) focusable. textArea.getCaret().setSelectionVisible(true); // Set the foreground color. Important because when rendering HTML, // default foreground becomes black, which may not match all LAF's // (e.g. Substance). Color fg = UIManager.getColor("Label.foreground"); if (fg == null || (isNimbus && isDerivedColor(fg))) { fg = SystemColor.textText; } textArea.setForeground(fg); // Make it use the "tool tip" background color. textArea.setBackground(TipUtil.getToolTipBackground()); // Force JEditorPane to use a certain font even in HTML. // All standard LookAndFeels, even Nimbus (!), define Label.font. Font font = UIManager.getFont("Label.font"); if (font == null) { // Try to make a sensible default font = new Font("SansSerif", Font.PLAIN, 12); } HTMLDocument doc = (HTMLDocument) textArea.getDocument(); setFont(doc, font, fg); // Always add link foreground rule. Unfortunately these CSS rules // stack each time the LaF is changed (how can we overwrite them // without clearing out the important "standard" ones?). Color linkFG = RSyntaxUtilities.getHyperlinkForeground(); doc.getStyleSheet().addRule("a { color: " + getHexString(linkFG) + "; }"); }
public StyledHTMLEditorPane() { this.setContentType("text/html"); this.document = (HTMLDocument) this.getDocument(); this.setDocument(document); Constants.loadSimpleStyle(document.getStyleSheet()); }
@Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { panel.history.goTo(Integer.parseInt(e.getDescription())); panel.refresh(); } else { final Element element = e.getSourceElement(); final int start = element.getStartOffset(); final int length = element.getEndOffset() - start; final HTMLDocument html = ((HTMLDocument) getDocument()); if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) { html.setParagraphAttributes(start, length, hoverAttr, false); } if (e.getEventType() == HyperlinkEvent.EventType.EXITED) { html.setParagraphAttributes(start, length, normalAttr, false); } } }
private void addHTML(String html) { synchronized (kit) { try { kit.insertHTML(doc, doc.getLength(), html, 0, 0, null); } catch (BadLocationException | IOException ignored) { Logger.logError(ignored.getMessage(), ignored); } displayArea.setCaretPosition(displayArea.getDocument().getLength()); } }
@Override public void write(int b) throws IOException { try { htmlKit.insertHTML( htmlDoc, htmlDoc.getLength(), new String(new byte[] {(byte) b}), 0, 0, null); } catch (BadLocationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public void printProps() { Dictionary<Object, Object> dic = htmlDoc.getDocumentProperties(); Enumeration e = dic.keys(); while (e.hasMoreElements()) { Object keyObj = e.nextElement(); Object valObj = dic.get(keyObj); logger.debug(keyObj + " " + valObj); } }
/** * Scrolls the help browser to the element with id <code>id</code> * * @param id the id * @return true, if an element with this id was found and scrolling was successful; false, * otherwise */ protected boolean scrollToElementWithId(String id) { Document d = help.getDocument(); if (d instanceof HTMLDocument) { HTMLDocument doc = (HTMLDocument) d; Element element = doc.getElement(id); try { Rectangle r = help.modelToView(element.getStartOffset()); if (r != null) { Rectangle vis = help.getVisibleRect(); r.height = vis.height; help.scrollRectToVisible(r); return true; } } catch (BadLocationException e) { Main.warn(tr("Bad location in HTML document. Exception was: {0}", e.toString())); e.printStackTrace(); } } return false; }
/** * Sets the font used for HTML displays to the specified font. Components that display HTML do not * necessarily honor font properties, since the HTML document can override these values. Calling * {@code setHtmlFont} after the data is set will force the HTML display to use the font specified * to this method. * * @param doc the HTML document to update * @param font the font to use * @throws NullPointerException if any parameter is {@code null} */ public static void setHtmlFont(HTMLDocument doc, Font font) { String stylesheet = String.format(STYLESHEET, font.getName(), font.getSize(), font.getName(), font.getSize()); try { doc.getStyleSheet().loadRules(new StringReader(stylesheet), null); } catch (IOException e) { // this should never happen with our sheet throw new IllegalStateException(e); } }
public String getPlainText() { try { StringWriter stringWriter = new StringWriter(); HTMLEditorKit htmlEditorKit = new HTMLEditorKit(); htmlEditorKit.write(stringWriter, document, 0, document.getLength()); return stringWriter.toString(); } catch (Exception e) { ExceptionHandler.log(e); } return null; }
/** * Sets the default font for an HTML document (e.g., in a tool tip displaying HTML). This is here * because when rendering HTML, {@code setFont()} is not honored. * * @param doc The document to modify. * @param font The font to use. * @param fg The default foreground color. */ public static void setFont(HTMLDocument doc, Font font, Color fg) { doc.getStyleSheet() .addRule( "body { font-family: " + font.getFamily() + "; font-size: " + font.getSize() + "pt" + "; color: " + getHexString(fg) + "; }"); }