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); }
@Override public synchronized void run() { try { for (int i = 0; i < NUM_PIPES; i++) { while (Thread.currentThread() == reader[i]) { try { this.wait(100); } catch (InterruptedException ie) { } if (pin[i].available() != 0) { String input = this.readLine(pin[i]); appendMsg(htmlize(input)); if (textArea.getDocument().getLength() > 0) { textArea.setCaretPosition(textArea.getDocument().getLength() - 1); } } if (quit) { return; } } } } catch (Exception e) { Debug.error(me + "Console reports an internal error:\n%s", e.getMessage()); } }
// For compatibility with writers when talking to the JVM. public void write(char[] buffer, int offset, int length) { String text = new String(buffer, offset, length); SwingUtilities.invokeLater( () -> { try { pane.getDocument().insertString(pane.getDocument().getLength(), text, properties); } catch (Exception e) { } }); }
private void displayMessage(String text, AttributeSet as) { try { if (!text.endsWith("\n")) { text += "\n"; } jTextPaneDisplayMessages .getDocument() .insertString(jTextPaneDisplayMessages.getDocument().getLength(), text, as); jTextPaneDisplayMessages.setCaretPosition(jTextPaneDisplayMessages.getDocument().getLength()); } catch (BadLocationException ex) { } }
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); }
private void updateEditorView() { editorPane.setText(""); numParameters = 0; try { java.util.List elements = editableTemplate.getPrintfElements(); for (Iterator it = elements.iterator(); it.hasNext(); ) { PrintfUtil.PrintfElement el = (PrintfUtil.PrintfElement) it.next(); if (el.getFormat().equals(PrintfUtil.PrintfElement.FORMAT_NONE)) { appendText(el.getElement(), PLAIN_ATTR); } else { insertParameter( (ConfigParamDescr) paramKeys.get(el.getElement()), el.getFormat(), editorPane.getDocument().getLength()); } } } catch (Exception ex) { JOptionPane.showMessageDialog( this, "Invalid Format: " + ex.getMessage(), "Invalid Printf Format", JOptionPane.ERROR_MESSAGE); selectedPane = 1; printfTabPane.setSelectedIndex(selectedPane); updatePane(selectedPane); } }
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) { } }
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 appendToPane(String msg, Color c) { if (inputText.isEnabled()) { StyleContext sc = StyleContext.getDefaultStyleContext(); AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c); textArea.setCharacterAttributes(aset, false); textArea.replaceSelection(msg); textArea.setCaretPosition(textArea.getDocument().getLength()); } }
// Appends text to the end of the log, using the provided settings. Doesn't add a new line. private static void print(String message, SimpleAttributeSet settings) { try { outputText .getDocument() .insertString(outputText.getDocument().getLength(), message, settings); } catch (BadLocationException e) { try { outputText .getDocument() .insertString( outputText.getDocument().getLength(), "Couldn't insert message \"" + message + "\".", progErr); } catch (BadLocationException b) { // If you ever reach this error, something is seriously wrong, so just please swallow it and // ignore it. } } }
@Override protected void exportDone(JComponent source, Transferable data, int action) { if (action == TransferHandler.MOVE) { JTextPane aTextPane = (JTextPane) source; int sel_start = aTextPane.getSelectionStart(); int sel_end = aTextPane.getSelectionEnd(); Document doc = aTextPane.getDocument(); try { doc.remove(sel_start, sel_end - sel_start); } catch (BadLocationException e) { Debug.error(me + "exportDone: Problem while trying to remove text\n%s", e.getMessage()); } } }
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(); } }
public void caretUpdate(CaretEvent e) { // when the cursor moves on _textView // this method will be called. Then, we // must determine what the line number is // and update the line number view Element root = textView.getDocument().getDefaultRootElement(); int line = root.getElementIndex(e.getDot()); root = root.getElement(line); int col = root.getElementIndex(e.getDot()); lineNumberView.setText(line + ":" + col); // if text is selected then enable copy and cut boolean isSelection = e.getDot() != e.getMark(); copyAction.setEnabled(isSelection); cutAction.setEnabled(isSelection); }
private void insertParameter(ConfigParamDescr descr, String format, int pos) { try { StyledDocument doc = (StyledDocument) editorPane.getDocument(); // The component must first be wrapped in a style Style style = doc.addStyle("Parameter-" + numParameters, null); JLabel label = new JLabel(descr.getDisplayName()); label.setAlignmentY(0.8f); // make sure we line up label.setFont(new Font("Helvetica", Font.PLAIN, 14)); label.setForeground(Color.BLUE); label.setName(descr.getKey()); label.setToolTipText("key: " + descr.getKey() + " format: " + format); StyleConstants.setComponent(style, label); doc.insertString(pos, format, style); numParameters++; } catch (BadLocationException e) { } }
@Override protected Transferable createTransferable(JComponent c) { JTextPane aTextPane = (JTextPane) c; SikuliEditorKit kit = ((SikuliEditorKit) aTextPane.getEditorKit()); Document doc = aTextPane.getDocument(); int sel_start = aTextPane.getSelectionStart(); int sel_end = aTextPane.getSelectionEnd(); StringWriter writer = new StringWriter(); try { _copiedImgs.clear(); kit.write(writer, doc, sel_start, sel_end - sel_start, _copiedImgs); return new StringSelection(writer.toString()); } catch (Exception e) { Debug.error(me + "createTransferable: Problem creating text to copy\n%s", e.getMessage()); } return null; }
public InterpreterFrame() { super("Simple Lisp Interpreter"); // Create the menu menubar = buildMenuBar(); setJMenuBar(menubar); // Create the toolbar toolbar = buildToolBar(); // disable cut and copy actions cutAction.setEnabled(false); copyAction.setEnabled(false); // Setup text area for editing source code // and setup document listener so interpreter // is notified when current file modified and // when the cursor is moved. textView = buildEditor(); textView.getDocument().addDocumentListener(this); textView.addCaretListener(this); // set default key bindings bindKeyToCommand("ctrl C", "(buffer-copy)"); bindKeyToCommand("ctrl X", "(buffer-cut)"); bindKeyToCommand("ctrl V", "(buffer-paste)"); bindKeyToCommand("ctrl E", "(buffer-eval)"); bindKeyToCommand("ctrl O", "(file-open)"); bindKeyToCommand("ctrl S", "(file-save)"); bindKeyToCommand("ctrl Q", "(exit)"); // Give text view scrolling capability Border border = BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(3, 3, 3, 3), BorderFactory.createLineBorder(Color.gray)); JScrollPane topSplit = addScrollers(textView); topSplit.setBorder(border); // Create tabbed pane for console/problems consoleView = makeConsoleArea(10, 50, true); problemsView = makeConsoleArea(10, 50, false); tabbedPane = buildProblemsConsole(); // Plug the editor and problems/console together // using a split pane. This allows one to change // their relative size using the split-bar in // between them. splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topSplit, tabbedPane); // Create status bar statusView = new JLabel(" Status"); lineNumberView = new JLabel("0:0"); statusbar = buildStatusBar(); // Now, create the outer panel which holds // everything together outerpanel = new JPanel(); outerpanel.setLayout(new BorderLayout()); outerpanel.add(toolbar, BorderLayout.PAGE_START); outerpanel.add(splitPane, BorderLayout.CENTER); outerpanel.add(statusbar, BorderLayout.SOUTH); getContentPane().add(outerpanel); // tell frame to fire a WindowsListener event // but not to close when "x" button clicked. setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(this); // set minimised icon to use setIconImage(makeImageIcon("spi.png").getImage()); // setup additional internal functions InternalFunctions.setup_internals(interpreter, this); // set default window size Component top = splitPane.getTopComponent(); Component bottom = splitPane.getBottomComponent(); top.setPreferredSize(new Dimension(100, 400)); bottom.setPreferredSize(new Dimension(100, 200)); pack(); // load + run user configuration file (if there is one) String homedir = System.getProperty("user.home"); try { interpreter.load(homedir + "/.simplelisp"); } catch (FileNotFoundException e) { // do nothing if file does not exist! System.out.println("Didn't find \"" + homedir + "/.simplelisp\""); } textView.grabFocus(); setVisible(true); // redirect all I/O to problems/console redirectIO(); // start highlighter thread highlighter = new DisplayThread(250); highlighter.setDaemon(true); highlighter.start(); }
private void insertText(String text, AttributeSet set, int pos) { try { editorPane.getDocument().insertString(pos, text, set); } catch (BadLocationException ex) { } }
private void appendText(String text, AttributeSet set) { insertText(text, set, editorPane.getDocument().getLength()); }