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); }
public HelpUI(Frame parent, String title) { sidebar = new Sidebar(); sidebar.setBorder(new EmptyBorder(10, 10, 10, 10)); infoView = new JTextPane(); Dimension d1 = sidebar.getPreferredSize(); infoView.setPreferredSize(new Dimension(d1.width * 3, d1.height - 5)); infoView.setEditable(false); MouseAdapter ma = new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { SidebarOption sopt = (SidebarOption) me.getComponent(); if (sel != null) { sel.setSelected(false); sel.repaint(); } sel = sopt; sel.setSelected(true); sel.repaint(); renderInfo(); } }; general = new SidebarOption("General Info", HELP_GENERAL_LOC); general.addMouseListener(ma); sidebar.add(general); sidebar.add(Box.createVerticalStrut(scy(10))); artifact = new SidebarOption("Artifacts", HELP_ARTIFACTS_LOC); artifact.addMouseListener(ma); sidebar.add(artifact); sidebar.add(Box.createVerticalStrut(scy(10))); net = new SidebarOption("Networking", HELP_NET_LOC); net.addMouseListener(ma); sidebar.add(net); sidebar.add(Box.createVerticalStrut(scy(10))); gpl = new SidebarOption("License", HELP_GPL_LOC); gpl.addMouseListener(ma); sidebar.add(gpl); general.setSelected(true); sel = general; sidebar.add(Box.createVerticalGlue()); add(BorderLayout.WEST, sidebar); add(BorderLayout.CENTER, new JScrollPane(infoView)); setResizable(false); pack(); setLocationRelativeTo(parent); setTitle(title); renderInfo(); }
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 updateDisplay() { // first, set block colours textView.setBackground(getColour(backgroundColour("text-background-colour"))); textView.setForeground(getColour(foregroundColour("text-foreground-colour"))); textView.setCaretColor(getColour(foregroundColour("text-caret-colour"))); problemsView.setBackground(getColour(backgroundColour("problems-background-colour"))); problemsView.setForeground(getColour(foregroundColour("problems-foreground-colour"))); consoleView.setBackground(getColour(backgroundColour("console-background-colour"))); consoleView.setForeground(getColour(foregroundColour("console-foreground-colour"))); // second, set colours on the code! java.util.List<Lexer.Token> tokens = Lexer.tokenise(textView.getText(), true); int pos = 0; for (Lexer.Token t : tokens) { int len = t.toString().length(); if (t instanceof Lexer.RightBrace || t instanceof Lexer.LeftBrace) { highlightArea(pos, len, foregroundColour("text-brace-colour")); } else if (t instanceof Lexer.Strung) { highlightArea(pos, len, foregroundColour("text-string-colour")); } else if (t instanceof Lexer.Comment) { highlightArea(pos, len, foregroundColour("text-comment-colour")); } else if (t instanceof Lexer.Quote) { highlightArea(pos, len, foregroundColour("text-quote-colour")); } else if (t instanceof Lexer.Comma) { highlightArea(pos, len, foregroundColour("text-comma-colour")); } else if (t instanceof Lexer.Identifier) { highlightArea(pos, len, foregroundColour("text-identifier-colour")); } else if (t instanceof Lexer.Integer) { highlightArea(pos, len, foregroundColour("text-integer-colour")); } pos += len; } }
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 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) { } }
/** * Gets the displayed value, and uses the converter to convert the shared value to units this * instance is supposed to represent. If the displayed value and shared value are different, * then we turn off our document filter and update our value to match the shared value. We * re-enable the document filter afterwards. */ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); try { StyledDocument doc = getStyledDocument(); double actualValue = (multiplier.getDisplayValue(value.getValue())); String actualValueAsString = df.format(actualValue); String displayedValue; try { displayedValue = doc.getText(0, doc.getLength()); } catch (BadLocationException e) { displayedValue = ""; } if (displayedValue.isEmpty()) { displayedValue = "0"; } double displayedValueAsDouble = Double.parseDouble(displayedValue); if (!actualValueAsString.equals(displayedValue) && displayedValueAsDouble != actualValue) // Allow user to enter trailing zeroes. { bypassFilterAndSetText(doc, actualValueAsString); } } catch (NumberFormatException e) { // Swallow it as it's OK for the user to try and enter non-numbers. } }
private void renderInfo() { if (sel.rsc == null) { try { infoView.setPage(BLANK_PAGE); } catch (IOException e) { e.printStackTrace(); } return; } try { infoView.setPage(sel.rsc); } catch (IOException e) { e.printStackTrace(); } }
public void evaluate() { try { // clear problems and console messages problemsView.setText(""); consoleView.setText(""); // update status view statusView.setText(" Parsing ..."); tabbedPane.setSelectedIndex(0); LispExpr root = Parser.parse(textView.getText()); statusView.setText(" Running ..."); tabbedPane.setSelectedIndex(1); // update run button runButton.setIcon(stopImage); runButton.setActionCommand("Stop"); // start run thread runThread = new RunThread(root); runThread.start(); } catch (SyntaxError e) { tabbedPane.setSelectedIndex(0); System.err.println( "Syntax Error at " + e.getLine() + ", " + e.getColumn() + " : " + e.getMessage()); } catch (Error e) { // parsing error System.err.println(e.getMessage()); statusView.setText(" Errors."); } }
public void unbindKey(String keySequence) { KeyStroke ks = KeyStroke.getKeyStroke(keySequence); if (ks == null) { throw new Error("Invalid key sequence \"" + keySequence + "\""); } textView.getKeymap().removeKeyStrokeBinding(ks); }
private boolean checkForSave() { // build warning message String message; if (file == null) { message = "File has been modified. Save changes?"; } else { message = "File \"" + file.getName() + "\" has been modified. Save changes?"; } // show confirm dialog int r = JOptionPane.showConfirmDialog( this, new JLabel(message), "Warning!", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (r == JOptionPane.YES_OPTION) { // Save File if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { // write the file physWriteTextFile(fileChooser.getSelectedFile(), textView.getText()); } else { // user cancelled save after all return false; } } return r != JOptionPane.CANCEL_OPTION; }
public void prettyPrint() { try { // clear old problem messages problemsView.setText(""); // update status view statusView.setText(" Parsing ..."); LispExpr root = Parser.parse(textView.getText()); statusView.setText(" Pretty Printing ..."); String newText = PrettyPrinter.prettyPrint(root); textView.setText(newText); statusView.setText(" Done."); } catch (Error e) { System.err.println(e.getMessage()); statusView.setText(" Errors."); } }
public void bindKeyToCommand(String keySequence, LispExpr cmd) { // see Java API for info on keySequence format KeyStroke ks = KeyStroke.getKeyStroke(keySequence); if (ks == null) { throw new Error("Invalid key sequence \"" + keySequence + "\""); } textView.getKeymap().addActionForKeyStroke(ks, new KeyAction(cmd)); }
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) { } } }
public int getYValueFromOffset(int offset) { try { return textPane.modelToView(offset).y; } catch (Exception e) { System.out.println("EditorServer: DocumentPanel: getYValueFromOffset. error"); e.printStackTrace(); return 0; } }
public void newFile() { if (!dirty || checkForSave()) { textView.setText(""); consoleView.setText(""); problemsView.setText(""); statusView.setText(" Created new file."); file = null; // reset dirty bit dirty = false; } }
public void saveFile() { if (file == null) { // first save file, so prompt for name. saveFileAs(); } else { // file already named so just write it. physWriteTextFile(file, textView.getText()); // update status statusView.setText(" Saved file \"" + file.getName() + "\"."); // reset dirty bit dirty = false; } }
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); }
public void saveFileAs() { // Force user to enter new file name if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { file = fileChooser.getSelectedFile(); } else { // user cancelled save after all return; } // file selected, so write it. physWriteTextFile(file, textView.getText()); // update status statusView.setText(" Saved file \"" + file.getName() + "\"."); // reset dirty bit dirty = false; }
public void openFile() { if (!dirty || checkForSave()) { if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { file = fileChooser.getSelectedFile(); } else { // user cancelled open after all return; } // load file into text view textView.setText(physReadTextFile(file)); // update status statusView.setText(" Loaded file \"" + file.getName() + "\"."); // reset dirty bit dirty = false; } }
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) { } }
private void handleConnect() { if (jToggleButtonConnect.isSelected() || jMenuItemServerConnect.isEnabled()) try { jTextPaneDisplayMessages.setText(""); session = new Session(); try { String userid = jTextFieldUser.getText(); if (jPasswordFieldPwd.getPassword() != null) { String pwd = String.valueOf(jPasswordFieldPwd.getPassword()).trim(); if (!pwd.equals("")) { userid += ":" + pwd; } } if (session.connect(jTextFieldServer.getText(), userid)) { displayMessage("Connected\n", incomingMsgAttrSet); session.addListener(this); jToggleButtonConnect.setText("Disconnect"); jMenuItemServerConnect.setEnabled(false); jMenuItemServerDisconnect.setEnabled(true); } else { jToggleButtonConnect.setSelected(false); jMenuItemServerConnect.setEnabled(true); jMenuItemServerDisconnect.setEnabled(false); displayMessage("Connection attempt failed\n", offlineClientAttrSet); } } catch (ConnectionException ex1) { jToggleButtonConnect.setSelected(false); jMenuItemServerConnect.setEnabled(true); jMenuItemServerDisconnect.setEnabled(false); displayMessage( "Connection attempt failed: " + ex1.getMessage() + "\n", offlineClientAttrSet); } } catch (Exception ex) { ex.printStackTrace(); } else { disconnect(); jMenuItemServerConnect.setEnabled(true); jMenuItemServerDisconnect.setEnabled(false); displayMessage("Disconnected\n", offlineClientAttrSet); } }
void finishInit() { // Create 3 styles associated with the text panes Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE); StyleConstants.setFontFamily(def, "SansSerif"); Style regular0 = jTextPane.addStyle("regular", def); Style regular1 = commentPane.addStyle("regular", def); Style s0 = jTextPane.addStyle("old", regular0); Style s1 = commentPane.addStyle("old", regular1); StyleConstants.setBackground(s0, Color.yellow); StyleConstants.setBackground(s1, Color.yellow); s0 = jTextPane.addStyle("new", regular0); StyleConstants.setBackground(s0, Color.pink); s1 = commentPane.addStyle("new", regular1); StyleConstants.setBackground(s1, Color.pink); }
void insertMatchButton_actionPerformed(ActionEvent e) { String key = (String) matchComboBox.getSelectedItem(); String format = (String) matchesKeys.get(key); if (key.equals(STRING_LITERAL)) { format = escapeReservedChars( (String) JOptionPane.showInputDialog( this, "Enter the string you wish to match", "String Literal Input", JOptionPane.OK_CANCEL_OPTION)); if (StringUtil.isNullString(format)) { return; } } if (selectedPane == 0) { insertText(format, PLAIN_ATTR, editorPane.getSelectionStart()); } else { // add the combobox data value to the edit box int pos = formatTextArea.getCaretPosition(); formatTextArea.insert(format, pos); } }
public void actionPerformed(ActionEvent e) { textView.paste(); }
private JTextPane makeTextPane(boolean editable) { document = new DefaultStyledDocument(); JTextPane ta = new JTextPane(document); ta.setEditable(editable); return ta; }
public void actionPerformed(ActionEvent e) { textView.copy(); }
private JTextPane buildEditor() { // build the editor pane JTextPane ta = makeTextPane(true); ta.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 5)); return ta; }
public void setCaretPosition(int position) { Caret c = textView.getCaret(); // move the caret c.setDot(position); }
public int getCaretPosition() { Caret c = textView.getCaret(); return c.getDot(); }