Paste in JEditorPane

When doing a cut,copy, paste operation in my Editor Pane The text is being pasted on a new line and not in the selected location. I have set the EditorKit of the Editor pane as follows
setEditorKit(new HTMLEditorKit());
If i Comment this line of code the text is being pasted properly in the selected location. Can someone Please tell me a workaround to this. Which method of the EditorKit will I have to override in order for the text to be pasted in the selected location and not on the next link.
Any pointers in this regard will be greatly appreciated.i.e How do i paste the text on the same line when I set the EditorKit to HTMLEditorKit or for that matter some CustomizedHtmlEditorKit
Thanks in advance
gordon

If i write my CustomTransferHandler and assign that TransferHandler to my JEditorPane which method do I override and how in order to paste the cut code from my clipboard into my JEditorPane. What exact changes will I have to make to the following method
exportToClipboard(JComponent comp, Clipboard clip, int action)

Similar Messages

  • Disableing Copy and Paste in JEditorPane

    HI,
    how can I disable copy/Paste in JEditorPane ?

    Create a subclass of JEditorPane that overrides the paste() method to do nothing?

  • Problem in retreiving from database and viewing it in browser--urgent

    hai,
    i have develped an application using swings where the mails received from client and reply posted will be pasted in JEditorPane. all the mails,query and reply will be stored in database.
    then iam retrieving the mails from database and displaying it in browser using table data.(Just like forum). Iam using encodehtmltag function to omit the html tags that r present in the mail data.
    when i display it in browser it extends a page horizontically. how to avoid this. how to word wrap. one of my friend asked me to set number of character to be displayed per line. i did that. but problem is i could see the word break . i have set 90 characters to be displayed per line. i dont want to break the word. for eg., if the end string of a line is regarding it is displayed like this---reg and then arding in next line. how to avoid this.
    please help me iam breaking my head with this for past few days.

    If the field is a Date in your database, you can use the ResultSet.getDate() method, which will return a java.sql.Date (which extends java.util.Date).
    You can then use SimpleDateFormat to format it the way you like.
    See the API doc for more details.

  • JEditorPane and copy/paste

    Hello,
    I've got an applet with an editable JEditorPane.
    I can make a copy/paste in the editor from any application outside the applet and from the applet itself. But with Word under windows, the paste method tries to insert html rendered by word and it can't do that.
    Then I extended the TransferHandler class to make my own transfer handler, just to copy the text from a word selection. But doing that I can't do any copy/paste from the editor to the editor .... I don't understand ...
    public class MyTransferHandler extends TransferHandler {
         public boolean importData(JComponent comp, Transferable t)
         try {
              if (t.isDataFlavorSupported(new DataFlavor("text/plain;class=java.io.InputStream;charset=ISO-8859-1"))) {
              System.out.println("Flavor text/plain charset ISO-8859-1");
              InputStream data = (InputStream) t.getTransferData(new DataFlavor("text/plain;class=java.io.InputStream;charset=ISO-8859-1"));
              InputStreamReader isReader = new InputStreamReader(data);
              StringWriter strw = new StringWriter();
              int c;
              while ((c = isReader.read()) != -1) {
                   strw.write(c);
              //          System.out.println(strw.toString());
              SimpleHtmlWriter.this.editor.replaceSelection(strw.toString());
              } else if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
              System.out.println("Flavor string");
              String data = (String) t.getTransferData(DataFlavor.stringFlavor);
              //          System.out.println(data);
              SimpleHtmlWriter.this.editor.replaceSelection(data);
              return true;
         } catch (Exception e) {     
              e.printStackTrace();
              return false;
    Thanks a lot ...

    Or, you could use the cut, copy, paste methods of the JEditorPane.
    You can also use the DefaultEditorKit.CopyAction to create an Action to use on a button or menu item.

  • Cut, Copy and Paste + JEditorPane

    I am currently working on a text editor and i have now come to the cut, copy and paste "functions". When i try to compile my code i get:
    1. ERROR in MyMenu.java (at line 42)
    GUI.textarea.cut();
    ^^^
    The method cut() is undefined for the type JEditorPane
    2. ERROR in MyMenu.java (at line 47)
    GUI.textarea.copy();
    ^^^^
    The method copy() is undefined for the type JEditorPane
    3. ERROR in MyMenu.java (at line 51)
    GUI.textarea.paste();
    ^^^^^
    The method paste() is undefined for the type JEditorPane
    The code:
                             else if(event.getActionCommand().equals("Klipp ut")){
                             GUI.textarea.requestFocus();
                               GUI.textarea.cut();
                             else if(event.getActionCommand().equals("Kopiera")){
                             GUI.textarea.requestFocus();
                               GUI.textarea.copy();
                             else if(event.getActionCommand().equals("Klistra in")){
                             GUI.textarea.requestFocus();
                               GUI.textarea.paste();
                             }

    That didn't help me at all. I am trying to run the copy, paste and cut actions from my JMenubar. You can see my Jmenubar class code here.
    // Importerar det n�dv�ndiga
    import java.awt.*; import java.awt.event.*; import javax.swing.*;
    public class MyMenu extends JMenuBar
       // Arkivmenyn
       String fileItems[] = new String [] {"Nytt","�ppna","Spara","Spara som...","Avsluta"};
       char fileShortcuts[] = {'N','O','S','A','P','C','x'};
       char fileAccelerators[] = {};
       // Redigeramenyn
       String editItems[] = new String [] {"�ngra","G�r om","Klipp ut","Kopiera","Klistra in",
          "Rensa","Markera allt"};
       char editShortcuts[] = {'U','R','t','C','P','l','S'};
       char editAccelerators[] = {'Z','Y','X','C','V','\u0000','A'};
       // Konstruktorn
       MyMenu()
            // Namn till Menynraden
                   JMenu fileMenu = new JMenu("Arkiv");
                   JMenu editMenu = new JMenu("Redigera");
                   JMenu helpMenu = new JMenu("Hj�lp");
         // Kollar efter vilken meny som anv�ndaren g�r in p�
              ActionListener printListener = new ActionListener()
                           public void actionPerformed(ActionEvent event)
                             // Detta skall h�nda n�r anv�ndaren g�r in p� Avsluta
                             if(event.getActionCommand().equals("Avsluta")){System.exit(0);}
                             // Nytt
                             else if(event.getActionCommand().equals("Nytt") || event.getActionCommand().equals("Rensa")){
                                  GUI.textarea.setText("");
                             else if(event.getActionCommand().equals("Klipp ut")){
                               GUI.textarea.cut();
                             else if(event.getActionCommand().equals("Kopiera")){
                               GUI.textarea.copy();
                             else if(event.getActionCommand().equals("Klistra in")){
                               GUI.textarea.paste();
                             else if(event.getActionCommand().equals("�ppna")){
                               MyBrowser myBrowser = new MyBrowser();
                                 myBrowser.setVisible(false);
                             // Annars skall denna kodsnutt k�ras
                             else {System.out.println("Menu item["+event.getActionCommand()+"[pressed!");}
         // For-sats f�r att skapa Arkivmenyn
         for (int i=0;i<fileItems.length;i++)
            JMenuItem item = new JMenuItem(fileItems, fileShortcuts[i]);
         item.addActionListener(printListener);
         fileMenu.add(item);
         // Redigera-menyn
    for (int i=0;i<editItems.length;i++)
         JMenuItem item = new JMenuItem(editItems[i], editShortcuts[i]);
    if (editAccelerators[i] > ' ') // M�ste l�ggas till
    {item.setAccelerator(KeyStroke.getKeyStroke(editAccelerators[i],
    Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),false));}
         item.addActionListener(printListener);
         editMenu.add(item);
         // L�gger in tv� linjer i Redigeramenyn p� plats 2 och 9
    editMenu.insertSeparator(2);
    // L�gger till de skapade undermenyerna i menylisten
    add(fileMenu); add(editMenu); add(helpMenu);

  • Cut and Paste - Data Validation - JEditorPane

    I have an editor in development that uses JEditorPane which is supposed to accept only certain characters as its input.
    Now if I use keystroke I am able to handle the input data entered using keyboard and it seems this is not a good idea :(.
    But, for cut and paste this method does not work. So my questions are,
    1) What is a good way to do data validation for Paste operations
    2) I know that I might need to have a custom document but where do I do the validation in the custom document. I have checked using print statements and for my paste operation, it seems that the insert method in document does not get called.
    3) Is using system clipboard and checking the text before insertion a better option.
    4)What exactly happens when paste ie control C is pressed or paste from menu is clicked. I mean sequence of method calls.
    I know I have asked many questions but answers to any of them will be highly appreciated !!
    Thanks a lot for your help in advance :)

    In my application, I subclass JTextField but you should be able to change it to JEditorPane. Here is a snippet of code that you need:
    public class myTextField extends JTextField implements ClipboardOwner {
       public boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
          if (ks==KeyStroke.getKeyStroke(KeyEvent.VK_V,2)) {     // CTRL-V (paste text from clipboard)
             pasteText();
             return true;
          }   // there is more to my code but this will do
          return super.processKeyBinding(ks,e,condition,pressed);
       private void pasteText() {
          try {
             Transferable contents=clipboard.getContents(this);
             if (contents==null) return;
             int i=getCaretPosition();
             String line=(String)contents.getTransferData(DataFlavor.stringFlavor);
             String tmp=getText();
             int sStart=getSelectionStart();
             int sEnd=getSelectionEnd();
             if (sStart>=0) {
                setText(tmp.substring(0,sStart)+line+tmp.substring(sEnd));
                i=sStart;
             } else {
                if (i<tmp.length()) line+=tmp.substring(i);
                setText(tmp.substring(0,i)+line);
             sEnd=Math.min(i+line.length(),getText().length());
             setCaretPosition(sEnd);
             select(i,sEnd);
          } catch (Throwable t) {
             if (ExtDB!=null) ExtDB.setError("",t);
       public void lostOwnership(Clipboard cb, Transferable transferable) {
    }The above has been formatted to look pretty, the following is more suitable for cut-n-paste:
    public class myTextField extends JTextField implements ClipboardOwner {
       public boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
          if (ks==KeyStroke.getKeyStroke(KeyEvent.VK_V,2)) {     // CTRL-V (paste text from clipboard)
             pasteText();
             return true;
          }   // there is more to my code but this will do
          return super.processKeyBinding(ks,e,condition,pressed);
       private void pasteText() {
          try {
             Transferable contents=clipboard.getContents(this);
             if (contents==null) return;
             int i=getCaretPosition();
             String line=(String)contents.getTransferData(DataFlavor.stringFlavor);
             String tmp=getText();
             int sStart=getSelectionStart();
             int sEnd=getSelectionEnd();
             if (sStart>=0) {
                setText(tmp.substring(0,sStart)+line+tmp.substring(sEnd));
                i=sStart;
             } else {
                if (i<tmp.length()) line+=tmp.substring(i);
                setText(tmp.substring(0,i)+line);
             sEnd=Math.min(i+line.length(),getText().length());
             setCaretPosition(sEnd);
             select(i,sEnd);
          } catch (Throwable t) {
             if (ExtDB!=null) ExtDB.setError("",t);
       public void lostOwnership(Clipboard cb, Transferable transferable) {
    }This will force the paste action to trigger a call to insertString.
    ;o)
    V.V.
    PS: my preference for the use of processKeyBinding has been labled inappropriate, the proper method according to the experts in this forum is to use a combination of InputMap/ActionMap.... so, you decide what you want to do.

  • How can I copy and paste (styled) text in JTextPane/JEditorPane?

    I have a styled text in my editor and I use the copy and the paste action in JTextPane, but i am not able to paste again with previous text formatting(it inserts same text, but with logical attributes - formatting at caret/inserted/ position)
    I use RTFEditor kit.
    Is it possible to put information about styled text into clipboard and paste it back? Shall I simulate clipboard somehow?
    Please help
    Thanks for any suggestion
    Vity

    This [url http://forum.java.sun.com/thread.jsp?forum=57&thread=197091]thread contains a discussion on this topic with a few suggestions. I haven't tried them so I don't know how they work. I found the thread by searching the forum with the keywords "+copy +style +jtextpane".

  • Inserting big text in a JEditorPane / HTMLDOcument

    Hi.
    I have noticed a strange behaivour of a JEditorPane with an HTMLDocument in it.
    If i put a big text in it AT ONCE (setText() or insertString() or insetHTML, doesnt matter),
    the preformance of the whole app gets soooo slow, f.e if i type in just a single character afterwards, i takes about 3 seconds till it appears in the document.
    BUT if i put the big text into smaller pieces, f.e i paste in all the small text-parts, then i cant see
    any performance-problems afterwards.
    Has anybody an idea why it is like that ?!?
    Or do i something wrong when i put in the text at once ?
    (Im using the actual JDK1.4.0 and JRE1.4.0 b92)
    Thanks for help,
    greetings,
    Huni.

    Hello Andrea!
    You have to use a variable like TV or a text channel for every column you want to set. There is no direct way to fill a cell. In your script you only have to set the variable or channel. As you expected you have to use a vbCRLF to get multiline text. DIAdem will display multiline text but did not recognize it. That means that the program do not make a vertical alignment. The first line will be vertical centerted and all other lines will be below. Result: A white gap above the text! You have to 'play' with the cell and text height to get a half-decent text display. BTW: I made my tests with DIAdem 9.
    Matthias
    Matthias Alleweldt
    Project Engineer / Projektingenieur
    Twigeater?  

  • From jtextpane to jeditorpane

    I'd like to create a complete text editor so, i made these two code, but the first it's based on jtextpane and the second on a jeditorpane. I want to link toghether the second with the firt code , to have a cpmplete text editor. The problem is that i don't know how to do this. The fisrt think i thought to do was transform the jtext in the fisrt code in a jeditor but jeditor don't recognize the function 'append' .. Could someone help me? Thanks
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package GUI;
    import java.awt.Toolkit;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.StringSelection;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    import javax.swing.filechooser.FileNameExtensionFilter;
    * @author Elena
    public class Form extends javax.swing.JFrame {
    String ClipboardData = "";
    private Object CurrentFileDirectory;
    * Creates new form Form
    public Form() {
    initComponents();
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane2 = new javax.swing.JScrollPane();
    editorpane = new javax.swing.JEditorPane();
    jMenuBar1 = new javax.swing.JMenuBar();
    Open = new javax.swing.JMenu();
    New = new javax.swing.JMenuItem();
    Openfile = new javax.swing.JMenuItem();
    Save = new javax.swing.JMenuItem();
    SaveAs = new javax.swing.JMenuItem();
    Exit = new javax.swing.JMenuItem();
    Cut = new javax.swing.JMenu();
    jMenuItem6 = new javax.swing.JMenuItem();
    Copy = new javax.swing.JMenuItem();
    Paste = new javax.swing.JMenuItem();
    Delete = new javax.swing.JMenuItem();
    SelectAll = new javax.swing.JMenuItem();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Java Text Editor");
    jScrollPane2.setViewportView(editorpane);
    Open.setText("File");
    New.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
    New.setText("New");
    New.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    NewActionPerformed(evt);
    Open.add(New);
    Openfile.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
    Openfile.setText("Open...");
    Openfile.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    OpenfileActionPerformed(evt);
    Open.add(Openfile);
    Save.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
    Save.setText("Save");
    Save.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    SaveActionPerformed(evt);
    Open.add(Save);
    SaveAs.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
    SaveAs.setText("Save As...");
    SaveAs.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    SaveAsActionPerformed(evt);
    Open.add(SaveAs);
    Exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_0, java.awt.event.InputEvent.CTRL_MASK));
    Exit.setText("Exit");
    Exit.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    ExitActionPerformed(evt);
    Open.add(Exit);
    jMenuBar1.add(Open);
    Cut.setText("Edit");
    jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
    jMenuItem6.setText("Cut");
    jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jMenuItem6ActionPerformed(evt);
    Cut.add(jMenuItem6);
    Copy.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
    Copy.setText("Copy");
    Copy.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    CopyActionPerformed(evt);
    Cut.add(Copy);
    Paste.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
    Paste.setText("Paste");
    Paste.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    PasteActionPerformed(evt);
    Cut.add(Paste);
    Delete.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DELETE, 0));
    Delete.setText("Delete");
    Delete.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    DeleteActionPerformed(evt);
    Cut.add(Delete);
    SelectAll.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
    SelectAll.setText("Select All");
    SelectAll.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    SelectAllActionPerformed(evt);
    Cut.add(SelectAll);
    jMenuBar1.add(Cut);
    setJMenuBar(jMenuBar1);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 479, Short.MAX_VALUE)
    pack();
    }// </editor-fold>
    private void NewActionPerformed(java.awt.event.ActionEvent evt) {                                   
    editorpane.setText("");
    private void ExitActionPerformed(java.awt.event.ActionEvent evt) {                                    
    System.exit(0);
    private void DeleteActionPerformed(java.awt.event.ActionEvent evt) {                                      
    editorpane.replaceSelection("");
    private void SaveAsActionPerformed(java.awt.event.ActionEvent evt) {                                      
    JFileChooser sdChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX File", "txt");
    sdChooser.setFileFilter(filter);
    int returnVal = sdChooser.showSaveDialog(null);
    try{
    if(returnVal == JFileChooser.APPROVE_OPTION){
    File directory = sdChooser.getCurrentDirectory();
    String path = directory.getAbsolutePath();
    String fileName = sdChooser.getSelectedFile().getName();
    if(fileName.contains(".docx")){
    }else{
    fileName = fileName + ".docx";
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "\\" + fileName)));
    bw.write(editorpane.getText());
    bw.close();
    } catch(IOException e){
    JOptionPane.showMessageDialog(null, "ERROR!");
    private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {                                          
    ClipboardData = editorpane.getSelectedText();
    StringSelection stringSelection = new StringSelection(ClipboardData);
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(stringSelection, null);
    editorpane.replaceSelection("");
    private void CopyActionPerformed(java.awt.event.ActionEvent evt) {                                    
    ClipboardData = editorpane.getSelectedText();
    StringSelection stringSelection = new StringSelection(ClipboardData);
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(stringSelection, null);
    private void PasteActionPerformed(java.awt.event.ActionEvent evt) {                                     
    editorpane.append(ClipboardData);
    private void SelectAllActionPerformed(java.awt.event.ActionEvent evt) {                                         
    editorpane.selectAll();
    private void OpenfileActionPerformed(java.awt.event.ActionEvent evt) {                                        
    JFileChooser opChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX file", "docx");
    opChooser.setFileFilter(filter);
    int returnval = opChooser.showOpenDialog(null);
    File chosenFile = opChooser.getSelectedFile();
    try {
    if(returnval == JFileChooser.APPROVE_OPTION){
    BufferedReader br = new BufferedReader(new FileReader(chosenFile));
    editorpane.setText("");
    String data;
    while((data = br.readLine()) != null) {
    editorpane.append(data + "\n");}
    br.close();
    }catch(IOException e){
    JOptionPane.showMessageDialog(null, "ERROR!" );
    private void SaveActionPerformed(java.awt.event.ActionEvent evt) {                                    
    if("".equals(CurrentFileDirectory)){
    JFileChooser sdChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX file", "docx");
    sdChooser.setFileFilter(filter);
    int returnval = sdChooser.showOpenDialog(null);
    try{
    if(returnval == JFileChooser.APPROVE_OPTION){
    File directory = sdChooser.getCurrentDirectory();
    String path = directory.getAbsolutePath();
    String fileName = sdChooser.getSelectedFile().getName();
    if(fileName.contains(".docx")){
    }else{
    fileName = fileName + ".docx";
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "\\" + fileName)));
    bw.write(editorpane.getText());
    bw.close();}
    }catch(IOException e){     
    JOptionPane.showMessageDialog(null, "ERROR!");
    * @param args the command line arguments
    public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
    * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
    try {
    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
    if ("Nimbus".equals(info.getName())) {
    javax.swing.UIManager.setLookAndFeel(info.getClassName());
    break;
    } catch (ClassNotFoundException ex) {
    java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
    java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    //</editor-fold>
    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
    new Form().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JMenuItem Copy;
    private javax.swing.JMenu Cut;
    private javax.swing.JMenuItem Delete;
    private javax.swing.JMenuItem Exit;
    private javax.swing.JMenuItem New;
    private javax.swing.JMenu Open;
    private javax.swing.JMenuItem Openfile;
    private javax.swing.JMenuItem Paste;
    private javax.swing.JMenuItem Save;
    private javax.swing.JMenuItem SaveAs;
    private javax.swing.JMenuItem SelectAll;
    private javax.swing.JEditorPane editorpane;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GraphicsEnvironment;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Action;
    import javax.swing.JButton;
    import javax.swing.JColorChooser;
    import javax.swing.JComboBox;
    import javax.swing.JDialog;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.Element;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.StyledEditorKit;
    public class Colore {
    public Colore() {
    JFrame frame = new JFrame();
    JTextPane textPane = new JTextPane();
    JScrollPane scrollPane = new JScrollPane(textPane);
    JPanel north = new JPanel();
    JMenuBar menu = new JMenuBar();
    JMenu styleMenu = new JMenu();
    styleMenu.setText("Style");
    Action boldAction = new BoldAction();
    boldAction.putValue(Action.NAME, "Bold");
    styleMenu.add(boldAction);
    Action italicAction = new ItalicAction();
    italicAction.putValue(Action.NAME, "Italic");
    styleMenu.add(italicAction);
    Action foregroundAction = new ForegroundAction();
    foregroundAction.putValue(Action.NAME, "Color");
    styleMenu.add(foregroundAction);
    Action formatTextAction = new FontAndSizeAction();
    formatTextAction.putValue(Action.NAME, "Font and Size");
    styleMenu.add(formatTextAction);
    menu.add(styleMenu);
    north.add(menu);
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(north, BorderLayout.NORTH);
    frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
    frame.setSize(800, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    public static void main(String[] args) {
    new Culo();
    class BoldAction extends StyledEditorKit.StyledTextAction {
    private static final long serialVersionUID = 9174670038684056758L;
    public BoldAction() {
    super("font-bold");
    public String toString() {
    return "Bold";
    public void actionPerformed(ActionEvent e) {
    JEditorPane editor = getEditor(e);
    if (editor != null) {
    StyledEditorKit kit = getStyledEditorKit(editor);
    MutableAttributeSet attr = kit.getInputAttributes();
    boolean bold = (StyleConstants.isBold(attr)) ? false : true;
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setBold(sas, bold);
    setCharacterAttributes(editor, sas, false);
    class ItalicAction extends StyledEditorKit.StyledTextAction {
    private static final long serialVersionUID = -1428340091100055456L;
    public ItalicAction() {
    super("font-italic");
    public String toString() {
    return "Italic";
    public void actionPerformed(ActionEvent e) {
    JEditorPane editor = getEditor(e);
    if (editor != null) {
    StyledEditorKit kit = getStyledEditorKit(editor);
    MutableAttributeSet attr = kit.getInputAttributes();
    boolean italic = (StyleConstants.isItalic(attr)) ? false : true;
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setItalic(sas, italic);
    setCharacterAttributes(editor, sas, false);
    class ForegroundAction extends StyledEditorKit.StyledTextAction {
    private static final long serialVersionUID = 6384632651737400352L;
    JColorChooser colorChooser = new JColorChooser();
    JDialog dialog = new JDialog();
    boolean noChange = false;
    boolean cancelled = false;
    public ForegroundAction() {
    super("foreground");
    public void actionPerformed(ActionEvent e) {
    JTextPane editor = (JTextPane) getEditor(e);
    if (editor == null) {
    JOptionPane.showMessageDialog(null,
    "You need to select the editor pane before you can change the color.", "Error",
    JOptionPane.ERROR_MESSAGE);
    return;
    int p0 = editor.getSelectionStart();
    StyledDocument doc = getStyledDocument(editor);
    Element paragraph = doc.getCharacterElement(p0);
    AttributeSet as = paragraph.getAttributes();
    fg = StyleConstants.getForeground(as);
    if (fg == null) {
    fg = Color.BLACK;
    colorChooser.setColor(fg);
    JButton accept = new JButton("OK");
    accept.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    fg = colorChooser.getColor();
    dialog.dispose();
    JButton cancel = new JButton("Cancel");
    cancel.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    cancelled = true;
    dialog.dispose();
    JButton none = new JButton("None");
    none.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    noChange = true;
    dialog.dispose();
    JPanel buttons = new JPanel();
    buttons.add(accept);
    buttons.add(none);
    buttons.add(cancel);
    dialog.getContentPane().setLayout(new BorderLayout());
    dialog.getContentPane().add(colorChooser, BorderLayout.CENTER);
    dialog.getContentPane().add(buttons, BorderLayout.SOUTH);
    dialog.setModal(true);
    dialog.pack();
    dialog.setVisible(true);
    if (!cancelled) {
    MutableAttributeSet attr = null;
    if (editor != null) {
    if (fg != null && !noChange) {
    attr = new SimpleAttributeSet();
    StyleConstants.setForeground(attr, fg);
    setCharacterAttributes(editor, attr, false);
    }// end if color != null
    noChange = false;
    cancelled = false;
    private Color fg;
    class FontAndSizeAction extends StyledEditorKit.StyledTextAction {
    private static final long serialVersionUID = 584531387732416339L;
    private String family;
    private float fontSize;
    JDialog formatText;
    private boolean accept = false;
    JComboBox fontFamilyChooser;
    JComboBox fontSizeChooser;
    public FontAndSizeAction() {
    super("Font and Size");
    public String toString() {
    return "Font and Size";
    public void actionPerformed(ActionEvent e) {
    JTextPane editor = (JTextPane) getEditor(e);
    int p0 = editor.getSelectionStart();
    StyledDocument doc = getStyledDocument(editor);
    Element paragraph = doc.getCharacterElement(p0);
    AttributeSet as = paragraph.getAttributes();
    family = StyleConstants.getFontFamily(as);
    fontSize = StyleConstants.getFontSize(as);
    formatText = new JDialog(new JFrame(), "Font and Size", true);
    formatText.getContentPane().setLayout(new BorderLayout());
    JPanel choosers = new JPanel();
    choosers.setLayout(new GridLayout(2, 1));
    JPanel fontFamilyPanel = new JPanel();
    fontFamilyPanel.add(new JLabel("Font"));
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fontNames = ge.getAvailableFontFamilyNames();
    fontFamilyChooser = new JComboBox();
    for (int i = 0; i < fontNames.length; i++) {
    fontFamilyChooser.addItem(fontNames);
    fontFamilyChooser.setSelectedItem(family);
    fontFamilyPanel.add(fontFamilyChooser);
    choosers.add(fontFamilyPanel);
    JPanel fontSizePanel = new JPanel();
    fontSizePanel.add(new JLabel("Size"));
    fontSizeChooser = new JComboBox();
    fontSizeChooser.setEditable(true);
    fontSizeChooser.addItem(new Float(4));
    fontSizeChooser.addItem(new Float(8));
    fontSizeChooser.addItem(new Float(12));
    fontSizeChooser.addItem(new Float(16));
    fontSizeChooser.addItem(new Float(20));
    fontSizeChooser.addItem(new Float(24));
    fontSizeChooser.setSelectedItem(new Float(fontSize));
    fontSizePanel.add(fontSizeChooser);
    choosers.add(fontSizePanel);
    JButton ok = new JButton("OK");
    ok.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    accept = true;
    formatText.dispose();
    family = (String) fontFamilyChooser.getSelectedItem();
    fontSize = Float.parseFloat(fontSizeChooser.getSelectedItem().toString());
    JButton cancel = new JButton("Cancel");
    cancel.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    formatText.dispose();
    JPanel buttons = new JPanel();
    buttons.add(ok);
    buttons.add(cancel);
    formatText.getContentPane().add(choosers, BorderLayout.CENTER);
    formatText.getContentPane().add(buttons, BorderLayout.SOUTH);
    formatText.pack();
    formatText.setVisible(true);
    MutableAttributeSet attr = null;
    if (editor != null && accept) {
    attr = new SimpleAttributeSet();
    StyleConstants.setFontFamily(attr, family);
    StyleConstants.setFontSize(attr, (int) fontSize);
    setCharacterAttributes(editor, attr, false);

    Sorry. My problem is that I want to insert HTML inside the body tag of an HTML page, and I don't know any simple method to get a reference to the <body> element from the JEditorPane widget, I get a reference to the actual HTML document but I can't get a reference of a tag from HTMLDocument either. Thanks.
    Juanjo

  • JEditorPane split

    Hi all ,
    I have a problem with JEditorPane, I would split it in pages .
    I mean , i load a StyledDocument from a file and I would show only a page a time, I tried a copy and paste tecnique .
    the whole file is in a JEditorPane and the single page is copied in another JEP that is showed.
    this is the code :
         public void split(JTextPane from, JTextPane to,int fromWhere ,int toWhere,int jepFromWhere){
              from.select(fromWhere,fromWhere+toWhere);
              from.copy();
              to.setCaretPosition(jepFromWhere);
              to.paste();
         public void setDoc(DefaultStyledDocument document){
              this.doc = document;
              jep.setVisible(false);
              textPaneAppoggio.setDocument(document);
              stateChanged=false;
              stop = true;
              while( how < doc.getLength() && howmuch >0){
                   split(textPaneAppoggio,jep,how,howmuch,jepHow);
                   if (stateChanged){
                        stateChanged = false;
                   }else{
                   how = how+howmuch;
                   jepHow = jepHow+howmuch;
              stop = false;
              jep.setVisible(true);
              return ;
    public void adjustmentValueChanged(AdjustmentEvent e) {
         if(!stateChanged && stop){
              jep.setCaretPosition(jep.getDocument().getLength());
         if (e.getValue()!=0){
              howmuch = 0;
              jep.select( how , jep.getCaretPosition() - e.getValue());
                 jep.cut();
                    return ;
              jep.select( how , jep.getCaretPosition() - e.getValue());
              jep.cut();
              howmuch = howmuch /2;
              stateChanged = true;
         thanks for the replies !!!

    the error is that sometimes the doc setting isn't stopped so the scrolling is done.
    I tried the set AutoScroll feature but nothing different appened the JScrollPane scrolls anyway

  • Insert links in jeditorpane

    Hi,
    I am working on an applet that allow a user to edit simple HTML.
    The user can basicly enter plain text, and there are buttons that bold and add links.
    I have also made Enter insert a break tag.
    The code works fine EXCEPT in one case.
    If a user pastes in some text, that has newlines in it, and selects the first word after a newline to become a link, the link appears on the line above where it should be.
    The strange thing is that when I print the jeditorpane text, it looks fine, it just does not display in the pane correctly.
    The code I use is
    editor.replaceSelection("");
    kit.insertHTML( doc, start, "<a href=\"" + link + "\">" + text + "</a>", 0, 0, HTML.Tag.A );
    HOWEVER if I change to
    kit.insertHTML( doc, start, "<a href=\"" + link + "\">" + text + "</a>", 1, 1, HTML.Tag.A );
    I.e. change 0,0 to 1,1 it displays properly BUT only in the case where the word selected is just after a newline.
    I catch Ctrl-V keypresses, to ensure that the user only pastes in the plaintext version of what they are pasting. The problem would be solved if I could replace the newlines with break tags at this stage, but if I do that, the tags appear in the text.
    So (finally) my questions are.
    a) Is there a way to see check for the newline character being before the word selected?
    b) Or is there a way to make the default pasteaction handle break tags as markup rather than plain characters.
    Thanks
    wbxv

    a) Is there a way to see check for the newline character being before the word selected?You can try something like this:
    String newline=System.getProperty("line.separator");
    if (text.startsWith(newline)) text=text.substring(newline.length());
    editor.replaceSelection("");
    kit.insertHTML( doc, start, "<a href=\"" + link + "\">" + text + "</a>", 0, 0, HTML.Tag.A );
    b) Or is there a way to make the default pasteaction handle break tags as markup rather than plain
    characters.You can try something like this:
    int i=text_to_paste.indexOf(newline);   // newline is defined above
    if (i>=0) text_to_paste=text_to_paste.substring(0,i)+"<br>"+text_to_paste.substring(i+newline.length());You can make a loop to replace all newlines with <br> if you like.
    Hope this helps...
    V.V.

  • Set in JEditorPane

    hello when iam copying a word for (ex: kiran's) from Microsoft word and pasted it in a html file.
    And if i display that file in JEditorPane ,then
    it is displaying kiran's as
    kiran(and a small square here)s
    so the apostraphe is being replaced by a small square.
    how can i rectify this problem and the ' is displayed in it.
    thankyou.kiran

    I had the same problem today. It seems that when I pasted the MS Word document into the HTML file, the apostrophe was translated as a character other that the ASCII apostrophe. They look almost the same but the character code is obviously different. You will have to go through the HTML file and replace the "MS Word" apostrophes with the regular apostrophe. That did the trick for me.

  • Pasting big text in text area

    Hello everybody,
    I have a simple program:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class TextPane extends JFrame {
    JButton b = new JButton("Add Text");
    JEditorPane tp = new JEditorPane();
    public void init() {
    Container cp = getContentPane();
    tp.setSize(200,200);
    cp.add(new JScrollPane(tp);
    public static void main(String[] args) {
    TextPane frame = new TextPane();
    frame.init();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.setSize(500,500);
    frame.setVisible(true);
    I start it with -Xmx48m and if I try to paste 5mb text in the JEditorPane I have OutOfMemory. With 64MB I succeed to paste it, but Task manager shows that the program is using 80 MB of memory (before the paste it uses 13MB)! If I want to paste 10MB I need to start the program with 128MB heap and if I paste it consumes 150MB memory (again 13MB before this)! I have the same results with JTextArea and JTextPane.
    Why these text components need so much memory to handle big text areas and is there a way to avoid this?

    What's going on here, nobody can answer this....
    I tried with 3 different SUN JDK versions, I tried with IBM JDK, the results are the same. It seems that it's not a problem of the JDK, but a problem of the language itself. If you want to work in your text editor with more than 1 MB text don't use JAVA.... Or use a machine with 4-5 GB RAM at least....

  • Paste html4 in HTMLDocument.

    Hi,
    I've rewritten the paste function and if i detect a text/html flavor in contents of the system clipboard, i insert data in a htmldocument using text/html flavor (instead of string dataflavor).
    But many applications generate html 4 and htmleditorkit works with html 3.2
    So the result can be rather ugly because some tags aren't recognized.
    I would appreciate any help to solve this problem

    Hi,
    the only way to solve this is to implement own extensions/replacements to HTMLDocument, HTMLDocument.HTMLReader, HTMLEditorKit, JEditorPane and HTMLWriter. There were rumours that Java 1.5 (Tiger) due in late 2003 will have enhanced HTML support.
    Meanwhile see application SimplyHTML at http://www.lightdev.com/template.php4?id=3 for an example and documentation of how to do own extensions (SimplyHTML implements support for the SPAN tag and has some enhancement to table rendering).
    Ulrich

  • Jeditor pane cut, copy, paste

    I have an applet using jeditor panes. when you right click a popup shows and you can choose to cut, copy, paste, select all. I use the functions copy, cut, paste, selectAll which jeditorpane inherits. This works properly in java 1.3X but in java 1.41 it is not working. Is there cliboard communication problems with java 1.41?

    Hi dhhyde,
    If you are having issues with your cutting, copying and pasting items from your iPad, you may want to try some things to troubleshoot.
    First, quit all running applications and test again -
    iOS: Force an app to close
    Next, I would try restarting the iPad -
    Turn your iOS device off and on (restart) and reset
    If the issue is still present, you may want to restore the iPad as a new device -
    How to erase your iOS device and then set it up as a new device or restore it from backups
    Thanks for using Apple Support Communities.
    Best,
    Brett L  

Maybe you are looking for

  • MSI GE60 2PL Cooling Question

    Hi there, I just bought a MSI GE60 Apache-629 Laptop. I Never owned a MSI Laptop but I am Very Satisfied so Far. Even though it doesn't have the NVidia GTX 860m , like the Apache Pro, I can Still Run Battlefield 4 on Medium Spec in 1920x1080. My Ques

  • Iphoto Slideshow Export Coming Out Blank

    I've tried multiple times to export a slideshow, from IPhoto, onto a cd onto a hard drive via usb port cd or wirelessly and without fail EVERYTIME the movie has spots where the music will still play but the photos disappear and it's black (blank). HE

  • Unresolved Kernel Trap - can't restart after reinstalling OS

    hi, i just zeroed out one partition on my G5 after backing up the files to another partition. i wanted to reinstall a clean OS. i wasn't able to install from the CD in the G5 - kept getting a weird broken apple logo and the computer fan would start t

  • Controlling ACTION in ChaRM

    Dear Experts, I'm very new to Change Request Management. I am using Solution Manager 7.0 EhP1 (ST - 24) I've configured ChaRM at client and it is functional. To simplify the things initially I have assigned all default roles to all ChaRM users. Now I

  • Cannot Connect to Server - Please Help!

    I have a MacBook w/Leopard and Parallels w/Windows XP. Everything has been working fine for over a year. After a recent trip (and using several different motel wifi connections) I cannot connect to our Windows based home server. The server is primari