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()); } }
/** Clear the log panel. */ public void clearLogPanel() { try { logPane.getDocument().remove(1, logPane.getDocument().getLength() - 1); } catch (BadLocationException e) { LoggerFactory.getLogger(ProcessUIPanel.class).error(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) { } }); }
/** * Add the provided text with the provided color to the GUI document * * @param text The text that will be added * @param color The color used to show the text */ public void print(String text, Color color) { StyleContext sc = StyleContext.getDefaultStyleContext(); AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, color); int len = logPane.getDocument().getLength(); try { logPane.setCaretPosition(len); logPane.getDocument().insertString(len, text + "\n", aset); } catch (BadLocationException e) { LoggerFactory.getLogger(ProcessUIPanel.class).error("Cannot show the log message", e); } logPane.setCaretPosition(logPane.getDocument().getLength()); }
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) { } }
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); } }
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 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()); } }
// 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. } } }
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()); } }
public static void appendToPane(JTextPane tp, String msg, Color c) { StyleContext sc = StyleContext.getDefaultStyleContext(); AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c); aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console"); aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED); int len = tp.getDocument().getLength(); tp.setCaretPosition(len); tp.setCharacterAttributes(aset, false); tp.replaceSelection(msg); }
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(); } }
@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()); } } }
public void displayClass(String classString) { displayDataState = DisplayDataState.INSIDE_CLASS; try { String currentText = jTextPane.getDocument().getText(0, jTextPane.getDocument().getLength()); if (currentText.equals(getOneColorFormattedOutput(classString))) { return; } } catch (BadLocationException e) { e.printStackTrace(); } clearText(); StyleConstants.setFontSize(style, 18); Document doc = new DefaultStyledDocument(); try { doc.insertString(doc.getLength(), getOneColorFormattedOutput(classString), style); } catch (BadLocationException e) { e.printStackTrace(); } jTextPane.setDocument(doc); }
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 void displayReducedClassesNames(List<String> classNamesToShow, String inputText) { displayDataState = DisplayDataState.CLASSES_LIST; clearText(); int matchIndex; String beforeMatch = ""; String match; String afterMatch = ""; StyleConstants.setFontSize(style, 18); StyleConstants.setForeground(style, ColorScheme.FOREGROUND_CYAN); Document doc = jTextPane.getDocument(); for (String className : classNamesToShow) { matchIndex = className.indexOf(inputText); if (matchIndex > -1) { beforeMatch = className.substring(0, matchIndex); match = className.substring(matchIndex, matchIndex + inputText.length()); afterMatch = className.substring(matchIndex + inputText.length(), className.length()); } else { // we are here by camel match // i.e. 2-3 letters that fits // to class name match = className; } try { doc.insertString(doc.getLength(), beforeMatch, style); StyleConstants.setBackground(style, ColorScheme.SELECTION_BG); doc.insertString(doc.getLength(), match, style); StyleConstants.setBackground(style, ColorScheme.BACKGROUND); doc.insertString(doc.getLength(), afterMatch + "\n", style); } catch (BadLocationException e) { e.printStackTrace(); } } jTextPane.setDocument(doc); }
/** * Builds the chat window by adding all fields and buttons as well as making the window visible. * It also adds listeners to all the buttons and a listener so that the default close operation * becomes a method call. */ private void buildChatWindow() { Dimension chatWindowDimension = new Dimension(500, 400); Dimension writeAreDimensions = new Dimension(0, 83); JPanel mainPanel = new JPanel(new GridBagLayout()); JPanel extrasPanel = new JPanel(); JScrollPane scrollDisplayArea = new JScrollPane(); displayArea = new JTextPane(); JEditorPane writeMessageArea = new JEditorPane(); JButton sendTextButton = new JButton("Send"); JButton sendFileButton = new JButton("Send file"); displayTextDocument = displayArea.getDocument(); GridBagConstraints c = new GridBagConstraints(); c.insets = new Insets(5, 5, 5, 5); c.fill = GridBagConstraints.BOTH; c.gridwidth = 2; c.weightx = 1; c.weighty = 1; c.gridx = 0; c.gridy = 0; scrollDisplayArea.add(displayArea); scrollDisplayArea.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scrollDisplayArea.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); mainPanel.add(scrollDisplayArea, c); c.gridwidth = 1; c.weightx = 0; c.weighty = 0; c.gridx = 0; c.gridy = 1; extrasPanel.setBackground(new Color(96, 92, 95)); mainPanel.add(extrasPanel, c); c.gridx = 1; c.gridy = 1; mainPanel.add(sendFileButton, c); c.weightx = 1; c.weighty = 0; c.gridx = 0; c.gridy = 2; writeMessageArea.setPreferredSize(writeAreDimensions); mainPanel.add(writeMessageArea, c); c.weightx = 0; c.weighty = 0; c.gridx = 1; c.gridy = 2; mainPanel.add(sendTextButton, c); setPreferredSize(chatWindowDimension); add(mainPanel); pack(); setVisible(true); sendTextButton.addActionListener( e -> { // TODO add XML colors and shit System.out.println("ChatGUI: Sending message: " + writeMessageArea.getText()); chat.sendMessage(writeMessageArea.getText()); writeMessageArea.setText(""); }); sendFileButton.addActionListener( e -> { // TODO send a file System.out.println("ChatGUI: Is supposed to send a file"); }); addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { closeChatWindowOperation(); } }); }
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(); }
public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JBubblePanel bubblePanel = new JBubblePanel(); JTextPane textPane = new JTextPane(); bubblePanel.setLayout(new BorderLayout()); bubblePanel.add(textPane, BorderLayout.CENTER); Font normalFont = new Font("Arial", Font.PLAIN, 12); Font boldFont = new Font("Arial", Font.BOLD, 12); SimpleAttributeSet normal = new SimpleAttributeSet(); SimpleAttributeSet bold = new SimpleAttributeSet(); StyleConstants.setBold(bold, true); try { textPane .getDocument() .insertString(textPane.getDocument().getLength(), "Your connection to ", normal); textPane .getDocument() .insertString(textPane.getDocument().getLength(), "cvs.dev.java.net ", bold); textPane .getDocument() .insertString( textPane.getDocument().getLength(), "failed. Here are a few possible reasons.\n\n", normal); textPane .getDocument() .insertString( textPane.getDocument().getLength(), " Your computer is may not be connected to the network.\n" + "* The CVS server name may be entered incorrectly.\n\n", normal); textPane .getDocument() .insertString( textPane.getDocument().getLength(), "If you still can not connect, please contact support at ", normal); textPane .getDocument() .insertString(textPane.getDocument().getLength(), "*****@*****.**", bold); textPane.getDocument().insertString(textPane.getDocument().getLength(), ".", normal); } catch (BadLocationException ex) { ex.printStackTrace(); } frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(bubblePanel, BorderLayout.CENTER); frame.setBounds(200, 300, 400, 360); frame.setVisible(true); }
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()); }