@Override protected Transferable createTransferable(JComponent c) { JTextPane aTextPane = (JTextPane) c; HTMLEditorKit kit = ((HTMLEditorKit) aTextPane.getEditorKit()); StyledDocument sdoc = aTextPane.getStyledDocument(); int sel_start = aTextPane.getSelectionStart(); int sel_end = aTextPane.getSelectionEnd(); int i = sel_start; StringBuilder output = new StringBuilder(); while (i < sel_end) { Element e = sdoc.getCharacterElement(i); Object nameAttr = e.getAttributes().getAttribute(StyleConstants.NameAttribute); int start = e.getStartOffset(), end = e.getEndOffset(); if (nameAttr == HTML.Tag.BR) { output.append("\n"); } else if (nameAttr == HTML.Tag.CONTENT) { if (start < sel_start) { start = sel_start; } if (end > sel_end) { end = sel_end; } try { String str = sdoc.getText(start, end - start); output.append(str); } catch (BadLocationException ble) { Debug.error(me + "Copy-paste problem!\n%s", ble.getMessage()); } } i = end; } return new StringSelection(output.toString()); }
private void updateTemplateFromEditor(PrintfTemplate template) { ArrayList params = new ArrayList(); String format = null; int text_length = editorPane.getDocument().getLength(); try { format = editorPane.getDocument().getText(0, text_length); } catch (BadLocationException ex1) { } Element section_el = editorPane.getDocument().getDefaultRootElement(); // Get number of paragraphs. int num_para = section_el.getElementCount(); for (int p_count = 0; p_count < num_para; p_count++) { Element para_el = section_el.getElement(p_count); // Enumerate the content elements int num_cont = para_el.getElementCount(); for (int c_count = 0; c_count < num_cont; c_count++) { Element content_el = para_el.getElement(c_count); AttributeSet attr = content_el.getAttributes(); // Get the name of the style applied to this content element; may be null String sn = (String) attr.getAttribute(StyleConstants.NameAttribute); // Check if style name match if (sn != null && sn.startsWith("Parameter")) { // we extract the label. JLabel l = (JLabel) StyleConstants.getComponent(attr); if (l != null) { params.add(l.getName()); } } } } template.setFormat(format); template.setTokens(params); }
/** * Writes out an end tag for the element. * * @param elem an Element * @exception IOException on any I/O error */ protected void endTag(Element elem) throws IOException { if (synthesizedElement(elem)) { return; } // write out end tags for item on stack closeOutUnwantedEmbeddedTags(elem.getAttributes()); if (inContent) { if (!newlineOutputed && !inPre) { writeLineSeparator(); } newlineOutputed = false; inContent = false; } if (!inPre) { indent(); } if (matchNameAttribute(elem.getAttributes(), HTML.Tag.PRE)) { inPre = false; } write('<'); write('/'); write(elem.getName()); write('>'); writeLineSeparator(); }
/** * Highlight lines to start or end delimiter. * * @param content the content to parse * @param line the line number * @throws BadLocationException if offsets are wrong */ protected void highlightLinesAfter(String content, int line) throws BadLocationException { int offset = m_RootElement.getElement(line).getEndOffset(); // Start/End delimiter not found, nothing to do int startDelimiter = -1; int endDelimiter = -1; if (getMultiLineComment()) { startDelimiter = indexOf(content, getMultiLineCommentStart(), offset); endDelimiter = indexOf(content, getMultiLineCommentEnd(), offset); } if (startDelimiter < 0) startDelimiter = content.length(); if (endDelimiter < 0) endDelimiter = content.length(); int delimiter = Math.min(startDelimiter, endDelimiter); if (delimiter < offset) return; // Start/End delimiter found, reapply highlighting int endLine = m_RootElement.getElementIndex(delimiter); for (int i = line + 1; i < endLine; i++) { Element branch = m_RootElement.getElement(i); Element leaf = m_Self.getCharacterElement(branch.getStartOffset()); AttributeSet as = leaf.getAttributes(); if (as.isEqual(DEFAULT_COMMENT)) applyHighlighting(content, i); } }
/** Replaces the current word token */ public void replaceWord(String newWord) { if (currentWordPos != -1) { try { /* ORIGINAL document.remove(currentWordPos, currentWordEnd - currentWordPos); document.insertString(currentWordPos, newWord, null); */ // Howard's Version for Ekit Element element = ((javax.swing.text.html.HTMLDocument) document).getCharacterElement(currentWordPos); AttributeSet attribs = element.getAttributes(); document.remove(currentWordPos, currentWordEnd - currentWordPos); document.insertString(currentWordPos, newWord, attribs); // End Howard's Version // Need to reset the segment document.getText(0, document.getLength(), text); } catch (BadLocationException ex) { throw new RuntimeException(ex.getMessage()); } // Position after the newly replaced word(s) // Position after the newly replaced word(s) first = true; currentWordPos = getNextWordStart(text, currentWordPos + newWord.length()); if (currentWordPos != -1) { currentWordEnd = getNextWordEnd(text, currentWordPos); nextWordPos = getNextWordStart(text, currentWordEnd); sentanceIterator.setText(text); sentanceIterator.following(currentWordPos); } else moreTokens = false; } }
@Override public void mouseClicked(MouseEvent me) { Element el = doc.getCharacterElement(viewToModel(me.getPoint())); if (el == null) return; AttributeSet as = el.getAttributes(); if (as.isDefined("ip")) { String ip = (String) as.getAttribute("ip"); ScriptException se = (ScriptException) as.getAttribute("exception"); Node node = net.getAtIP(ip); if (node == null) { Utility.displayError("Error", "Computer does not exist"); return; } String errorString = "--ERROR--\n" + "Error at line number " + se.getLineNumber() + " and column number " + se.getColumnNumber() + "\n" + se.getMessage(); new ScriptDialog( parentFrame, str -> { if (str != null) { node.setScript(str); } }, node.getScript(), errorString) .setVisible(true); } }
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; }
/** * Determine the area of the document whose syntax highlighting is impacted by the change of * source content * * @param offset The initial offset of the change * @param length The length of the change * @throws BadLocationException If the change processing fails */ public void processChangedLines(int offset, int length) throws BadLocationException { Element line; int startOffset = offset; int changeOffset = offset; int changeLength = length; MutableAttributeSet highlight = getStyle(InformSyntax.Normal.getName()); MutableAttributeSet tokenCheck = getStyle(InformSyntax.Normal.getName()); // Locate start of first highlight token at insert/remove offset if (changeOffset > 0) { // Check for the element before the insertion/removal point (offset-1) so if the // insertion/removal point is at the boundary of two elements we get the previous // highlight token not the following highlight token Element token = getCharacterElement(offset - 1); startOffset = token.getStartOffset(); highlight = (MutableAttributeSet) token.getAttributes(); tokenCheck = getStyle((String) highlight.getAttribute(AttributeSet.NameAttribute)); while (highlight.containsAttributes(tokenCheck) && changeOffset > 0) { changeOffset = startOffset; token = getCharacterElement(changeOffset - 1); startOffset = token.getStartOffset(); highlight = (MutableAttributeSet) token.getAttributes(); } } // Find the length of the text in the document impacted by the insert/remove. // The length of the text between the start of the first highlight token at the insert point // to the end of the current line plus the length of the text being inserted into the document. if (length > 0) { line = getParagraphElement(offset + length); } else { line = getParagraphElement(offset); } changeLength = line.getEndOffset() - changeOffset; applyHighlighting(changeOffset, changeLength); }
@Override public void mouseMoved(MouseEvent me) { Element el = doc.getCharacterElement(viewToModel(me.getPoint())); if (el == null) return; AttributeSet as = el.getAttributes(); if (as.isDefined("ip")) { setCursor(handCursor); } else { setCursor(defaultCursor); } }
/** * Writes out comments. * * @param elem an Element * @exception IOException on any I/O error * @exception BadLocationException if pos represents an invalid location within the document. */ protected void comment(Element elem) throws BadLocationException, IOException { AttributeSet as = elem.getAttributes(); if (matchNameAttribute(as, HTML.Tag.COMMENT)) { Object comment = as.getAttribute(HTML.Attribute.COMMENT); if (comment instanceof String) { writeComment((String) comment); } else { writeComment(null); } } }
/** * Creates a {@link View} for the specified <code>Element</code>. * * @param element the <code>Element</code> to create a <code>View</code> for * @return the <code>View</code> for the specified <code>Element</code> or <code>null</code> if * the type of <code>element</code> is not supported */ public View create(Element element) { View view = null; Object attr = element.getAttributes().getAttribute(StyleConstants.NameAttribute); if (attr instanceof HTML.Tag) { HTML.Tag tag = (HTML.Tag) attr; if (tag.equals(HTML.Tag.IMPLIED) || tag.equals(HTML.Tag.P)) { view = new MinParagraphView(element); } else if (tag.equals(HTML.Tag.OBJECT)) { view = new ConstObjectView(element, map); } } return (view != null ? view : super.create(element)); }
/* * Provide dummy implementations to suppress download and display of * related resources: - FRAMEs - IMAGEs TODO create better dummy * displays TODO suppress LINK somehow */ @Override public View create(Element elem) { Object o = elem.getAttributes().getAttribute(StyleConstants.NameAttribute); if (o instanceof HTML.Tag) { HTML.Tag kind = (HTML.Tag) o; if (kind == HTML.Tag.FRAME) { return new ComponentView(elem); } else if (kind == HTML.Tag.IMG) { return new ComponentView(elem); } } return super.create(elem); }
private Element process(final javax.swing.text.Element textElement) throws BadLocationException { if (textElement.isLeaf()) { final int endOffset = textElement.getEndOffset(); final int startOffset = textElement.getStartOffset(); final String text = textElement.getDocument().getText(startOffset, endOffset - startOffset); final Element result = new Element(); result.setElementType(LabelType.INSTANCE); result.setAttribute(AttributeNames.Core.NAMESPACE, AttributeNames.Core.VALUE, text); configureStyle(textElement.getAttributes(), result); return result; } final Band band = new Band(); configureStyle(textElement.getAttributes(), band); configureBand(textElement, band); final int size = textElement.getElementCount(); for (int i = 0; i < size; i++) { final Element element = process(textElement.getElement(i)); band.addElement(element); } return band; }
private void displayElements(Element el, int level) { for (int x = 0; x < level; x++) System.err.print("-"); System.err.println(); System.err.println("Element name " + el.getName()); AttributeSet attrSet = el.getAttributes(); Enumeration enumAttr = attrSet.getAttributeNames(); while (enumAttr != null && enumAttr.hasMoreElements()) { System.err.println(" attr value " + enumAttr.nextElement().toString()); } int childElemCt = el.getElementCount(); for (int ix = 0; ix < childElemCt; ix++) { Element el1 = el.getElement(ix); displayElements(el1, ++level); } }
@Override public void mouseMoved(MouseEvent event) { JTextPane textPane = (JTextPane) event.getSource(); Point point = new Point(event.getX(), event.getY()); int position = textPane.viewToModel(point); DefaultStyledDocument document = (DefaultStyledDocument) textPane.getDocument(); Element element = document.getCharacterElement(position); AttributeSet attributeSet = element.getAttributes(); String sLink = (String) attributeSet.getAttribute("link"); if (sLink != null) { textPane.setCursor(handCursor); } else { textPane.setCursor(textCursor); } }
/** @param formatter */ protected void setFormatterFromTextPane(final DataObjSwitchFormatter formatter) { // visit every character in the document text looking for fields // store characters not associated with components (jbutton) to make up the separator text DefaultStyledDocument doc = (DefaultStyledDocument) formatEditor.getStyledDocument(); String text = formatEditor.getText(); int docLen = doc.getLength(); int lastFieldPos = 0; Vector<DataObjDataField> fields = new Vector<DataObjDataField>(); // int cnt = 0; for (int i = 0; i < docLen; ++i) { Element element = doc.getCharacterElement(i); AttributeSet attrs = element.getAttributes(); Object obj = attrs.getAttribute(StyleConstants.ComponentAttribute); // System.out.print(String.format("i: %d, lastFieldPos: %d cnt: %d, F: %s", i, lastFieldPos, // cnt, (obj instanceof FieldDefinitionComp ? "Y" : "N"))); if (obj instanceof FieldDefinitionComp) { // System.out.println(cnt+" "+(obj instanceof FieldDefinitionComp)); // found button at the current position // create corresponding field String sepStr = (lastFieldPos <= i - 1) ? text.substring(lastFieldPos, i) : ""; FieldDefinitionComp fieldDefBtn = (FieldDefinitionComp) obj; DataObjDataField fmtField = fieldDefBtn.getValue(); fmtField.setSep(sepStr); fields.add(fmtField); // System.out.print(" Sep: ["+sepStr+"]"); lastFieldPos = i + 1; // cnt++; } } // XXX: what do we do with the remaining of the text? right now we ignore it // That's because we can't create an empty formatter field just to use the separator... DataObjDataField[] fieldsArray = new DataObjDataField[fields.size()]; for (int i = 0; i < fields.size(); ++i) { fieldsArray[i] = fields.elementAt(i); } DataObjDataFieldFormat singleFormatter = fieldsArray.length == 0 ? null : new DataObjDataFieldFormat("", tableInfo.getClassObj(), false, "", "", fieldsArray); formatter.setSingle(singleFormatter); }
private Element getChildElementByTagName( Element element, HTML.Tag searchTag, Map<String, String> searchAtrib) { int count = element.getElementCount(); for (int i = 0; i < count; i++) { Element childElem = element.getElement(i); AttributeSet attributes = childElem.getAttributes(); Object obj = attributes.getAttribute(StyleConstants.NameAttribute); if ((obj instanceof HTML.Tag) && ((obj == searchTag))) if (searchAtrib != null) { if (isElementAtribOk(childElem, searchAtrib)) return childElem; } else { return childElem; } } return null; }
/** @return */ public int findFieldButtonPosition() { DefaultStyledDocument doc = (DefaultStyledDocument) formatEditor.getStyledDocument(); int i, n = doc.getLength(); Object obj = null; for (i = 0; i < n; ++i) { Element element = doc.getCharacterElement(i); AttributeSet attrs = element.getAttributes(); obj = attrs.getAttribute(StyleConstants.ComponentAttribute); if (obj == this) { // found button at this position return i; } } // this should never happen because the button clicked must be inside text pane throw new RuntimeException("Button representing field in text pane was not found."); }
private void printAtribute(Element elem) { logger.debug("--------------------------------------------"); logger.debug("Elemn name : " + elem.getName()); AttributeSet as = elem.getAttributes(); Enumeration e = as.getAttributeNames(); while (e.hasMoreElements()) { Object key = e.nextElement(); if (key != null) { System.out.print(" atrName : " + key.toString() + " , "); Object val = as.getAttribute(key); if (val != null) System.out.print(" atrVal : " + val.toString()); logger.debug(" "); } } logger.debug("--------------------------------------------"); }
private Map<String, String> getAtributes(Element element, List<String> questionReadAtrib) { Map<String, String> foundAtrib = new HashMap<String, String>(); AttributeSet as = element.getAttributes(); Enumeration e = as.getAttributeNames(); while (e.hasMoreElements()) { Object keyObj = e.nextElement(); if (keyObj != null) { Object valObj = as.getAttribute(keyObj); if (valObj != null) if (questionReadAtrib.contains(String.valueOf(keyObj))) foundAtrib.put(String.valueOf(keyObj), String.valueOf(valObj)); } } return foundAtrib; }
private List<Element> getChildElementsByTagName( Element element, HTML.Tag searchTag, Map<String, String> searchAtrib) { int count = element.getElementCount(); List<Element> elemnts = new ArrayList<Element>(); for (int i = 0; i < count; i++) { Element childElem = element.getElement(i); AttributeSet attributes = childElem.getAttributes(); Object obj = attributes.getAttribute(StyleConstants.NameAttribute); if ((obj instanceof HTML.Tag) && ((obj == searchTag))) if (searchAtrib != null) { if (isElementAtribOk(childElem, searchAtrib)) elemnts.add(childElem); } else { elemnts.add(childElem); } } return elemnts; }
void editorPane_keyPressed(KeyEvent e) { StyledDocument doc = editorPane.getStyledDocument(); int pos = editorPane.getCaretPosition(); int code = e.getKeyCode(); Element el; switch (code) { case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_DELETE: case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: if (pos == 0) return; // we want to get the element to the left of position. el = doc.getCharacterElement(pos - 1); break; case KeyEvent.VK_RIGHT: case KeyEvent.VK_KP_RIGHT: // we want to get the element to the right of position. el = doc.getCharacterElement(pos + 1); break; default: return; // bail we don't handle it. } AttributeSet attr = el.getAttributes(); String el_name = (String) attr.getAttribute(StyleConstants.NameAttribute); int el_range = el.getEndOffset() - el.getStartOffset() - 1; if (el_name.startsWith("Parameter") && StyleConstants.getComponent(attr) != null) { try { switch (code) { case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_DELETE: doc.remove(el.getStartOffset(), el_range); break; case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: editorPane.setCaretPosition(pos - el_range); break; case KeyEvent.VK_RIGHT: case KeyEvent.VK_KP_RIGHT: editorPane.setCaretPosition(pos + (el_range)); break; } } catch (BadLocationException ex) { } } }
/* * Determine the Y offset for the current row */ private int getOffsetY(int rowStartOffset, FontMetrics fontMetrics) throws BadLocationException { // Get the bounding rectangle of the row Rectangle r = component.modelToView(rowStartOffset); int lineHeight = fontMetrics.getHeight(); int y = r.y + r.height; int descent = 0; // The text needs to be positioned above the bottom of the bounding // rectangle based on the descent of the font(s) contained on the row. if (r.height == lineHeight) { // default font is being used descent = fontMetrics.getDescent(); } else { // We need to check all the attributes for font changes if (fonts == null) { fonts = new HashMap<String, FontMetrics>(); } Element root = component.getDocument().getDefaultRootElement(); int index = root.getElementIndex(rowStartOffset); Element line = root.getElement(index); for (int i = 0; i < line.getElementCount(); i++) { Element child = line.getElement(i); AttributeSet as = child.getAttributes(); String fontFamily = (String) as.getAttribute(StyleConstants.FontFamily); Integer fontSize = (Integer) as.getAttribute(StyleConstants.FontSize); String key = fontFamily + fontSize; FontMetrics fm = fonts.get(key); if (fm == null) { Font font = new Font(fontFamily, Font.PLAIN, fontSize); fm = component.getFontMetrics(font); fonts.put(key, fm); } descent = Math.max(descent, fm.getDescent()); } } return y - descent; }
public void write(Writer out, Document doc, int pos, int len, Map<String, String> copiedImgs) throws IOException, BadLocationException { Debug.log(9, "SikuliEditorKit.write %d %d", pos, len); DefaultStyledDocument sdoc = (DefaultStyledDocument) doc; int i = pos; String absPath; while (i < pos + len) { Element e = sdoc.getCharacterElement(i); int start = e.getStartOffset(), end = e.getEndOffset(); if (e.getName().equals(StyleConstants.ComponentElementName)) { // A image argument to be filled AttributeSet attr = e.getAttributes(); Component com = StyleConstants.getComponent(attr); out.write(com.toString()); if (copiedImgs != null && (com instanceof EditorPatternButton || com instanceof EditorPatternLabel)) { if (com instanceof EditorPatternButton) { absPath = ((EditorPatternButton) com).getFilename(); } else { absPath = ((EditorPatternLabel) com).getFile(); } String fname = (new File(absPath)).getName(); copiedImgs.put(fname, absPath); Debug.log(3, "save image for copy&paste: " + fname + " -> " + absPath); } } else { if (start < pos) { start = pos; } if (end > pos + len) { end = pos + len; } out.write(doc.getText(start, end - start)); } i = end; } out.close(); }
/** @return - true got all atributes */ private boolean isElementAtribOk(Element element, Map<String, String> searchAtrib) { List<String> found = new ArrayList<String>(); // serach for all atrib from key list AttributeSet attributeSet = element.getAttributes(); Enumeration e = attributeSet.getAttributeNames(); while (e.hasMoreElements()) { Object keyObj = e.nextElement(); if (keyObj != null) if (keyObj instanceof HTML.Attribute) { Object valObj = attributeSet.getAttribute(keyObj); if (valObj != null) if (searchAtrib.get(String.valueOf(keyObj)) != null) { String valAtr = searchAtrib.get(String.valueOf(keyObj)); if (valObj.equals(valAtr)) found.add(String.valueOf(keyObj)); } } } // chek if got all if (found.size() != 0) if (found.containsAll(searchAtrib.keySet())) return true; return false; }
public void refresh() { final StringBuilder text = new StringBuilder(""); synchronized (this) { for (int i = 0; i < s.size(); ++i) { if (i == currentPosition) { text.append("<B>").append(str(i)).append("</B>"); } else { text.append(str(i)); } } } final HTMLDocument html = (HTMLDocument) getDocument(); Element body = null; final Element[] roots = html.getRootElements(); for (int i = 0; i < roots[0].getElementCount(); i++) { final Element element = roots[0].getElement(i); if (element.getAttributes().getAttribute(StyleConstants.NameAttribute) == HTML.Tag.BODY) { body = element; break; } } try { synchronized (this) { if (text.toString().equals("")) { html.setInnerHTML(body, " "); } else { html.setInnerHTML(body, text.toString()); } } } catch (final BadLocationException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } scrollDown(); }
private ActionListener getAction(final MouseEvent event) { Element e = document.getCharacterElement(textPane.viewToModel(event.getPoint())); ActionListener action = (ActionListener) e.getAttributes().getAttribute(ACTION_ATTRIBUTE); return action; }
/** * Check whether a given line is tagged with a given tag. * * @param line The line to check * @param tag The name of the tag * @return True, if the tag is set */ protected final boolean hasObject(Element line, String tag) { return line.getAttributes().getAttribute(tag) != null; }
public void actionPerformed(ActionEvent e) { JTextPane editor = (JTextPane) getEditor(e); int p0 = editor.getSelectionStart(); StyledDocument doc = getStyledDocument(editor); Element paragraph = doc.getCharacterElement(p0); AttributeSet as = paragraph.getAttributes(); family = StyleConstants.getFontFamily(as); fontSize = StyleConstants.getFontSize(as); formatText = new JDialog(new JFrame(), "Font and Size", true); formatText.getContentPane().setLayout(new BorderLayout()); JPanel choosers = new JPanel(); choosers.setLayout(new GridLayout(2, 1)); JPanel fontFamilyPanel = new JPanel(); fontFamilyPanel.add(new JLabel("Font")); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); String[] fontNames = ge.getAvailableFontFamilyNames(); fontFamilyChooser = new JComboBox<String>(); for (int i = 0; i < fontNames.length; i++) { fontFamilyChooser.addItem(fontNames[i]); } fontFamilyChooser.setSelectedItem(family); fontFamilyPanel.add(fontFamilyChooser); choosers.add(fontFamilyPanel); JPanel fontSizePanel = new JPanel(); fontSizePanel.add(new JLabel("Size")); fontSizeChooser = new JComboBox<Float>(); fontSizeChooser.setEditable(true); for (int size = 2; size <= 60; size += 2) { fontSizeChooser.addItem(new Float(size)); } fontSizeChooser.setSelectedItem(new Float(fontSize)); fontSizePanel.add(fontSizeChooser); choosers.add(fontSizePanel); JButton ok = new JButton("OK"); ok.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ae) { accept = true; formatText.dispose(); family = (String) fontFamilyChooser.getSelectedItem(); fontSize = Float.parseFloat(fontSizeChooser.getSelectedItem().toString()); } }); JButton cancel = new JButton("Cancel"); cancel.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ae) { formatText.dispose(); } }); JPanel buttons = new JPanel(); buttons.add(ok); buttons.add(cancel); formatText.getContentPane().add(choosers, BorderLayout.CENTER); formatText.getContentPane().add(buttons, BorderLayout.SOUTH); formatText.pack(); formatText.setVisible(true); MutableAttributeSet attr = null; if (editor != null && accept) { attr = new SimpleAttributeSet(); StyleConstants.setFontFamily(attr, family); StyleConstants.setFontSize(attr, (int) fontSize); setCharacterAttributes(editor, attr, false); } }
@Override public void mouseClicked(MouseEvent event) { if (event.getClickCount() == 2 && event.getSource() instanceof JList) { Cursor cursor = hydc3View.getCursor(); hydc3View.setCursor(new Cursor(Cursor.WAIT_CURSOR)); String s = hydc3View.getSelected(); try { hydc3View.clearDescriptionTextPane(); if (s.matches(".[0-9]+ .+")) { int index = Integer.parseInt(s.split(" ")[0].substring(1)); s = s.substring(0, 1); hydc3Model.getDescriptionsByCharacterAndIndex(s, index); } else if (s.length() == 1) { hydc3Model.getDescriptionsByCharacter(s); } else { hydc3Model.getDescriptionsByWord(s); } hydc3View.setDescriptionTextPaneTop(); } catch (Exception e) { e.printStackTrace(); } hydc3View.setCursor(cursor); } else if (event.getSource() instanceof JTextPane) { JTextPane textPane = (JTextPane) event.getSource(); Point point = new Point(event.getX(), event.getY()); int position = textPane.viewToModel(point); DefaultStyledDocument document = (DefaultStyledDocument) textPane.getDocument(); Element element = document.getCharacterElement(position); AttributeSet attributeSet = element.getAttributes(); String sLink = (String) attributeSet.getAttribute("link"); if (sLink != null) { Cursor cursor = hydc3View.getCursor(); hydc3View.setCursor(new Cursor(Cursor.WAIT_CURSOR)); try { if (sLink.matches(".")) { hydc3View.clearDescriptionTextPane(); hydc3Model.getDescriptionsByCharacter(sLink); hydc3View.setDescriptionTextPaneTop(); } else if (sLink.matches(".[0-9]+")) { int index = Integer.parseInt(sLink.substring(1)); hydc3View.clearDescriptionTextPane(); hydc3Model.getDescriptionsByCharacterAndIndex(sLink.substring(0, 1), index); hydc3View.setDescriptionTextPaneTop(); } else { HashMap<String, Integer> wordPositionMap = hydc3View.getWordPositionMap(); Integer iPosition = wordPositionMap.get(sLink); if (iPosition != null) { hydc3View.setDescriptionTextPaneCaretPosition(iPosition); } else { hydc3View.clearDescriptionTextPane(); hydc3Model.getDescriptionsByWord(sLink); hydc3View.setDescriptionTextPaneTop(); } } } catch (Exception e) { e.printStackTrace(); } hydc3View.setCursor(cursor); } } }