List of usage examples for javax.swing JTextArea replaceSelection
public void replaceSelection(String content)
From source file:Main.java
public static void main(String[] argv) throws Exception { JTextArea comp = new JTextArea(); String actionName = "Lowercase"; JFrame f = new JFrame(); f.add(new JScrollPane(comp)); f.setSize(300, 300);/*w w w .ja v a2s .c om*/ f.setVisible(true); comp.getInputMap().put(KeyStroke.getKeyStroke("F2"), actionName); comp.getActionMap().put(actionName, new TextAction(actionName) { public void actionPerformed(ActionEvent evt) { JTextComponent comp = getTextComponent(evt); if (comp.getSelectionStart() == comp.getSelectionEnd()) { if (comp.getCaretPosition() < comp.getDocument().getLength()) { try { int pos = comp.getCaretPosition(); Document doc = comp.getDocument(); String str = doc.getText(pos, 1).toLowerCase(); doc.remove(pos, 1); doc.insertString(pos, str, null); comp.moveCaretPosition(pos + 1); } catch (Exception e) { System.out.println(); } } } else { int s = comp.getSelectionStart(); int e = comp.getSelectionEnd(); comp.replaceSelection(comp.getSelectedText().toLowerCase()); comp.select(s, e); } } }); }
From source file:DragFileDemo.java
public boolean importData(JComponent c, Transferable t) { JTextArea tc; if (!canImport(c, t.getTransferDataFlavors())) { return false; }/*from w w w .j av a 2 s.c o m*/ //A real application would load the file in another //thread in order to not block the UI. This step //was omitted here to simplify the code. try { if (hasFileFlavor(t.getTransferDataFlavors())) { String str = null; java.util.List files = (java.util.List) t.getTransferData(fileFlavor); for (int i = 0; i < files.size(); i++) { File file = (File) files.get(i); //Tell the tabbedpane controller to add //a new tab with the name of this file //on the tab. The text area that will //display the contents of the file is returned. tc = tpc.addTab(file.toString()); BufferedReader in = null; try { in = new BufferedReader(new FileReader(file)); while ((str = in.readLine()) != null) { tc.append(str + newline); } } catch (IOException ioe) { System.out.println("importData: Unable to read from file " + file.toString()); } finally { if (in != null) { try { in.close(); } catch (IOException ioe) { System.out.println("importData: Unable to close file " + file.toString()); } } } } return true; } else if (hasStringFlavor(t.getTransferDataFlavors())) { tc = (JTextArea) c; if (tc.equals(source) && (tc.getCaretPosition() >= p0.getOffset()) && (tc.getCaretPosition() <= p1.getOffset())) { shouldRemove = false; return true; } String str = (String) t.getTransferData(stringFlavor); tc.replaceSelection(str); return true; } } catch (UnsupportedFlavorException ufe) { System.out.println("importData: unsupported data flavor"); } catch (IOException ieo) { System.out.println("importData: I/O exception"); } return false; }