List of usage examples for javax.swing.text Document insertString
public void insertString(int offset, String str, AttributeSet a) throws BadLocationException;
From source file:Main.java
public void actionPerformed(ActionEvent e) { JTextComponent comp = getTextComponent(e); if (comp == null) return;//from ww w .j a v a2 s. c o m Document doc = comp.getDocument(); int start = comp.getSelectionStart(); int end = comp.getSelectionEnd(); try { int left = Utilities.getWordStart(comp, start); int right = Utilities.getWordEnd(comp, end); String word = doc.getText(left, right - left); doc.remove(left, right - left); doc.insertString(left, word.toUpperCase(), null); comp.setSelectionStart(start); comp.setSelectionEnd(end); } catch (BadLocationException ble) { return; } }
From source file:de.unentscheidbar.validation.swing.trigger.DocumentChangeTriggerTest.java
@Override protected void provokeTrigger(Iterable<JTextComponent> components) { for (final JTextComponent c : components) { runInEdt(new Callable<Void>() { @Override/*from w ww . j ava 2s .c om*/ public Void call() throws Exception { Document doc = c.getDocument(); switch (rnd.nextInt(3)) { case 0: doc.remove(doc.getStartPosition().getOffset(), doc.getLength() / 2); break; case 1: doc.insertString(rnd.nextInt(Math.max(1, doc.getStartPosition().getOffset())), RandomStringUtils.randomAlphanumeric(1 + rnd.nextInt(10)), null); break; case 2: c.setText(UUID.randomUUID().toString()); break; default: Assert.fail(); } return null; } }); } drainEventQueue(); }
From source file:KeymapExample.java
public void actionPerformed(ActionEvent e) { JTextComponent comp = getTextComponent(e); if (comp == null) return;//from ww w. ja va2 s . co m Document doc = comp.getDocument(); int start = comp.getSelectionStart(); int end = comp.getSelectionEnd(); try { int left = javax.swing.text.Utilities.getWordStart(comp, start); int right = javax.swing.text.Utilities.getWordEnd(comp, end); String word = doc.getText(left, right - left); doc.remove(left, right - left); doc.insertString(left, word.toUpperCase(), null); comp.setSelectionStart(start); comp.setSelectionEnd(end); } catch (BadLocationException ble) { return; } }
From source file:dmh.swing.huxley.action.WrapTextAction.java
@Override public int manipulateText(Document document, int start, int end) { try {/*from w w w . j a v a 2 s .c o m*/ final int offset = start; final int length = end - start; // Extract the selected text. String selectedText = StringUtils.trimToEmpty(document.getText(offset, length)); document.remove(offset, length); // Re-insert the text, wrapped in tokens. String insertText = prefixToken + selectedText + suffixToken; document.insertString(offset, insertText, null); // Return the caret position. return start + ("".equals(selectedText) ? 1 : insertText.length()); } catch (BadLocationException e) { // This indicates a programming error. throw new RuntimeException(e); } }
From source file:dmh.swing.huxley.action.InsertHeadingAction.java
@Override public int manipulateText(Document document, int start, int end) { try {/* www.j a v a 2s . c o m*/ final int offset = start; final int length = end - start; // Extract the selected text. String title = StringUtils.trimToEmpty(document.getText(offset, length)); document.remove(offset, length); // Add the header. String bar = StringUtils.repeat(token, 40); String insertText = "\n " + title + "\n" + bar + "\n"; document.insertString(offset, insertText, null); // Return the caret position. return start + ("".equals(title) ? 2 : insertText.length()); } catch (BadLocationException e) { // This indicates a programming error. throw new RuntimeException(e); } }
From source file:com.adito.upgrade.GUIUpgrader.java
void appendString(String message, Color c) { Document doc = console.getDocument(); if (doc.getLength() != 0) { message = "\n" + message; }// w w w.java 2 s .co m SimpleAttributeSet attr = new SimpleAttributeSet(); StyleConstants.setForeground(attr, c); try { doc.insertString(doc.getLength(), message, attr); } catch (Exception e) { } console.setCaretPosition(doc.getLength()); console.scrollRectToVisible(console.getVisibleRect()); }
From source file:multiplayer.pong.client.LobbyFrame.java
private void appendMessage(String message, SimpleAttributeSet set) { // If no set of styles was passed, use the default if (set == null) set = new SimpleAttributeSet(); Document doc = ta.getStyledDocument(); try {/*www. j av a 2 s . c o m*/ doc.insertString(doc.getLength(), message, set); } catch (BadLocationException e) { } }
From source file:de.huxhorn.lilith.swing.preferences.PreferencesDialog.java
public void editDetailsFormatter() { Console console = new Console(); File messageViewRoot = applicationPreferences.getDetailsViewRoot(); File messageViewGroovyFile = new File(messageViewRoot, ApplicationPreferences.DETAILS_VIEW_GROOVY_FILENAME); EventWrapper<LoggingEvent> eventWrapper = new EventWrapper<>( new SourceIdentifier("identifier", "secondaryIdentifier"), 17, new LoggingEvent()); console.setVariable("eventWrapper", eventWrapper); console.setCurrentFileChooserDir(messageViewRoot); String text = ""; if (!messageViewGroovyFile.isFile()) { applicationPreferences.initDetailsViewRoot(true); }/*from w w w. ja va 2 s .c o m*/ if (messageViewGroovyFile.isFile()) { InputStream is; try { is = new FileInputStream(messageViewGroovyFile); List lines = IOUtils.readLines(is, StandardCharsets.UTF_8); boolean isFirst = true; StringBuilder textBuffer = new StringBuilder(); for (Object o : lines) { String s = (String) o; if (isFirst) { isFirst = false; } else { textBuffer.append("\n"); } textBuffer.append(s); } text = textBuffer.toString(); } catch (IOException e) { if (logger.isInfoEnabled()) { logger.info("Exception while reading '" + messageViewGroovyFile.getAbsolutePath() + "'.", e); } } } else { if (logger.isWarnEnabled()) logger.warn("Failed to initialize detailsView file '{}'!", messageViewGroovyFile.getAbsolutePath()); } console.run(); // initializes everything console.setScriptFile(messageViewGroovyFile); JTextPane inputArea = console.getInputArea(); //inputArea.setText(text); Document doc = inputArea.getDocument(); try { doc.remove(0, doc.getLength()); doc.insertString(0, text, null); } catch (BadLocationException e) { if (logger.isWarnEnabled()) logger.warn("Exception while setting source!", e); } console.setDirty(false); inputArea.setCaretPosition(0); inputArea.requestFocusInWindow(); }
From source file:edu.ku.brc.af.ui.forms.formatters.DataObjFieldFormatSinglePanel.java
/** * @param singleFormatter/*from w w w. j a v a 2s . c o m*/ */ protected void fillWithObjFormatter(final DataObjDataFieldFormatIFace singleFormatter) { ignoreFmtChange = true; try { formatEditor.setText(""); if (singleFormatter == null) { return; } Document doc = formatEditor.getDocument(); DataObjDataField[] fields = singleFormatter.getFields(); if (fields == null) { return; } for (DataObjDataField field : fields) { try { doc.insertString(doc.getLength(), field.getSep(), null); //System.err.println("["+field.getName()+"]["+field.getSep()+"]["+field.getFormat()+"]["+field.toString()+"]"); insertFieldIntoTextEditor(new DataObjDataFieldWrapper(field)); } catch (BadLocationException ble) { } } } finally { ignoreFmtChange = false; } }
From source file:edu.virginia.iath.oxygenplugins.juel.JUELPluginMenu.java
public JUELPluginMenu(StandalonePluginWorkspace spw, LocalOptions ops) { super(name, true); ws = spw;//from ww w . j av a 2 s .c om options = ops; // setup the options //options.readStorage(); // Find names JMenuItem search = new JMenuItem("Find Name"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { String label = "Find Name"; final JTextField lastName = new JTextField("", 30); lastName.setPreferredSize(new Dimension(350, 25)); //JTextField projectName = new JTextField("", 30); final JComboBox possibleVals = new JComboBox(); possibleVals.setEnabled(false); possibleVals.setPreferredSize(new Dimension(350, 25)); JButton search = new JButton("Search"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { // query the database try { String json = ""; String line; URL url = new URL("http://juel.iath.virginia.edu/academical_db/people/find_people?term=" + lastName.getText()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { json += line; } JSONArray obj = new JSONArray(json); // Read the JSON and update possibleVals possibleVals.removeAllItems(); possibleVals.setEnabled(false); for (int i = 0; i < obj.length(); i++) { JSONObject cur = obj.getJSONObject(i); String name = cur.getString("label"); String id = String.format("P%05d", cur.getInt("value")); possibleVals.addItem(new ComboBoxObject(name, id)); possibleVals.setEnabled(true); } } catch (Exception e) { e.printStackTrace(); possibleVals.setEnabled(false); } return; } }); search.setPreferredSize(new Dimension(100, 25)); JButton insert = new JButton("Insert"); insert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent sel) { // Insert into the page // Get the selected value, grab the ID, then insert into the document // Get the editor WSTextEditorPage ed = null; WSEditor editorAccess = ws .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA); if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) { ed = (WSTextEditorPage) editorAccess.getCurrentPage(); } String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\""; // Update the text in the document ed.beginCompoundUndoableEdit(); int selectionOffset = ed.getSelectionStart(); ed.deleteSelection(); javax.swing.text.Document doc = ed.getDocument(); try { if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" ")) result = " " + result; if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ") && !doc.getText(selectionOffset, 1).equals(">")) result = result + " "; doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY); } catch (javax.swing.text.BadLocationException b) { // Okay if it doesn't work } ed.endCompoundUndoableEdit(); return; } }); insert.setPreferredSize(new Dimension(100, 25)); java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1); java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns JPanel addPanel = new JPanel(); JPanel addPanelInner = new JPanel(); addPanel.setLayout(layoutOuter); addPanel.add(new JLabel("Search for last name, then choose a full name from the list below")); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Search Last Name: ")); addPanelInner.add(lastName); addPanelInner.add(search); addPanel.add(addPanelInner); addPanelInner = new JPanel(); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Narrow Search: ")); addPanelInner.add(possibleVals); addPanelInner.add(insert); addPanel.add(addPanelInner); JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label, JOptionPane.PLAIN_MESSAGE); } }); this.add(search); // Find places search = new JMenuItem("Find Place"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { String label = "Find Place"; final JTextField searchText = new JTextField("", 30); searchText.setPreferredSize(new Dimension(350, 25)); //JTextField projectName = new JTextField("", 30); final JComboBox possibleVals = new JComboBox(); possibleVals.setEnabled(false); possibleVals.setPreferredSize(new Dimension(350, 25)); JButton search = new JButton("Search"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { // query the database try { String json = ""; String line; URL url = new URL( "http://academical.village.virginia.edu/academical_db/places/find_places?term=" + searchText.getText()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { json += line; } JSONArray obj = new JSONArray(json); // Read the JSON and update possibleVals possibleVals.removeAllItems(); possibleVals.setEnabled(false); for (int i = 0; i < obj.length(); i++) { JSONObject cur = obj.getJSONObject(i); String id = String.format("PL%04d", cur.getInt("value")); String name = cur.getString("label") + " (" + id + ")"; possibleVals.addItem(new ComboBoxObject(name, id)); possibleVals.setEnabled(true); } } catch (Exception e) { e.printStackTrace(); possibleVals.setEnabled(false); } return; } }); search.setPreferredSize(new Dimension(100, 25)); JButton insert = new JButton("Insert"); insert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent sel) { // Insert into the page // Get the selected value, grab the ID, then insert into the document // Get the editor WSTextEditorPage ed = null; WSEditor editorAccess = ws .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA); if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) { ed = (WSTextEditorPage) editorAccess.getCurrentPage(); } String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\""; // Update the text in the document ed.beginCompoundUndoableEdit(); int selectionOffset = ed.getSelectionStart(); ed.deleteSelection(); javax.swing.text.Document doc = ed.getDocument(); try { if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" ")) result = " " + result; if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ") && !doc.getText(selectionOffset, 1).equals(">")) result = result + " "; doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY); } catch (javax.swing.text.BadLocationException b) { // Okay if it doesn't work } ed.endCompoundUndoableEdit(); return; } }); insert.setPreferredSize(new Dimension(100, 25)); java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1); java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns JPanel addPanel = new JPanel(); JPanel addPanelInner = new JPanel(); addPanel.setLayout(layoutOuter); addPanel.add(new JLabel("Search for a place name, then choose one from the list below")); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Search Keyword: ")); addPanelInner.add(searchText); addPanelInner.add(search); addPanel.add(addPanelInner); addPanelInner = new JPanel(); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Narrow Search: ")); addPanelInner.add(possibleVals); addPanelInner.add(insert); addPanel.add(addPanelInner); JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label, JOptionPane.PLAIN_MESSAGE); } }); this.add(search); // Find corporate bodies search = new JMenuItem("Find Corporate Body"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { String label = "Find Corporate Body"; final JTextField searchText = new JTextField("", 30); searchText.setPreferredSize(new Dimension(350, 25)); //JTextField projectName = new JTextField("", 30); final JComboBox possibleVals = new JComboBox(); possibleVals.setEnabled(false); possibleVals.setPreferredSize(new Dimension(350, 25)); JButton search = new JButton("Search"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { // query the database try { String json = ""; String line; URL url = new URL( "http://academical.village.virginia.edu/academical_db/corporate_bodies/find?term=" + searchText.getText()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { json += line; } JSONArray obj = new JSONArray(json); // Read the JSON and update possibleVals possibleVals.removeAllItems(); possibleVals.setEnabled(false); for (int i = 0; i < obj.length(); i++) { JSONObject cur = obj.getJSONObject(i); String id = String.format("CB%04d", cur.getInt("value")); String name = cur.getString("label") + " (" + id + ")"; possibleVals.addItem(new ComboBoxObject(name, id)); possibleVals.setEnabled(true); } } catch (Exception e) { e.printStackTrace(); possibleVals.setEnabled(false); } return; } }); search.setPreferredSize(new Dimension(100, 25)); JButton insert = new JButton("Insert"); insert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent sel) { // Insert into the page // Get the selected value, grab the ID, then insert into the document // Get the editor WSTextEditorPage ed = null; WSEditor editorAccess = ws .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA); if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) { ed = (WSTextEditorPage) editorAccess.getCurrentPage(); } String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\""; // Update the text in the document ed.beginCompoundUndoableEdit(); int selectionOffset = ed.getSelectionStart(); ed.deleteSelection(); javax.swing.text.Document doc = ed.getDocument(); try { if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" ")) result = " " + result; if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ") && !doc.getText(selectionOffset, 1).equals(">")) result = result + " "; doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY); } catch (javax.swing.text.BadLocationException b) { // Okay if it doesn't work } ed.endCompoundUndoableEdit(); return; } }); insert.setPreferredSize(new Dimension(100, 25)); java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1); java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns JPanel addPanel = new JPanel(); JPanel addPanelInner = new JPanel(); addPanel.setLayout(layoutOuter); addPanel.add(new JLabel("Search for a corporate body, then one from the list below")); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Search Keyword: ")); addPanelInner.add(searchText); addPanelInner.add(search); addPanel.add(addPanelInner); addPanelInner = new JPanel(); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Narrow Search: ")); addPanelInner.add(possibleVals); addPanelInner.add(insert); addPanel.add(addPanelInner); JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label, JOptionPane.PLAIN_MESSAGE); } }); this.add(search); // Find Courses search = new JMenuItem("Find Course"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { String label = "Find Course"; final JTextField searchText = new JTextField("", 30); searchText.setPreferredSize(new Dimension(350, 25)); //JTextField projectName = new JTextField("", 30); final JComboBox possibleVals = new JComboBox(); possibleVals.setEnabled(false); possibleVals.setPreferredSize(new Dimension(350, 25)); JButton search = new JButton("Search"); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent selection) { // query the database try { String json = ""; String line; URL url = new URL( "http://academical.village.virginia.edu/academical_db/courses/find?term=" + searchText.getText()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { json += line; } JSONArray obj = new JSONArray(json); // Read the JSON and update possibleVals possibleVals.removeAllItems(); possibleVals.setEnabled(false); for (int i = 0; i < obj.length(); i++) { JSONObject cur = obj.getJSONObject(i); String id = String.format("C%04d", cur.getInt("value")); String name = cur.getString("label") + " (" + id + ")"; possibleVals.addItem(new ComboBoxObject(name, id)); possibleVals.setEnabled(true); } } catch (Exception e) { e.printStackTrace(); possibleVals.setEnabled(false); } return; } }); search.setPreferredSize(new Dimension(100, 25)); JButton insert = new JButton("Insert"); insert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent sel) { // Insert into the page // Get the selected value, grab the ID, then insert into the document // Get the editor WSTextEditorPage ed = null; WSEditor editorAccess = ws .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA); if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) { ed = (WSTextEditorPage) editorAccess.getCurrentPage(); } String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\""; // Update the text in the document ed.beginCompoundUndoableEdit(); int selectionOffset = ed.getSelectionStart(); ed.deleteSelection(); javax.swing.text.Document doc = ed.getDocument(); try { if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" ")) result = " " + result; if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ") && !doc.getText(selectionOffset, 1).equals(">")) result = result + " "; doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY); } catch (javax.swing.text.BadLocationException b) { // Okay if it doesn't work } ed.endCompoundUndoableEdit(); return; } }); insert.setPreferredSize(new Dimension(100, 25)); java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1); java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns JPanel addPanel = new JPanel(); JPanel addPanelInner = new JPanel(); addPanel.setLayout(layoutOuter); addPanel.add(new JLabel("Search for a course, then choose one from the list below")); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Search Keyword: ")); addPanelInner.add(searchText); addPanelInner.add(search); addPanel.add(addPanelInner); addPanelInner = new JPanel(); addPanelInner.setLayout(layout); addPanelInner.add(new JLabel("Narrow Search: ")); addPanelInner.add(possibleVals); addPanelInner.add(insert); addPanel.add(addPanelInner); JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label, JOptionPane.PLAIN_MESSAGE); } }); this.add(search); }