JTextPane + HTMLEditorKit withe space problem

cc_Frauenstein

Neues Mitglied
Hallo zusammen ich möchte ein Editor programmieren der Syles unterstützt und alles im HTML Format in eine Database speichern und wieder laden kann jetzt funktioniert das ganze nur das TextPane sich seltsam verhält.

Ich mache zB. folgende Zeilen:
11111
22222

und nach speichern/laden/speichern/laden erhalte ich

11111 22222

was ist das für ein Bug von Java das ist ja eine Qual folgend kommt der Quellcode:


TextFrame.java
Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.HashMap;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;

import ag.ion.bion.officelayer.application.IApplicationAssistant;
import ag.ion.bion.officelayer.application.ILazyApplicationInfo;
import ag.ion.bion.officelayer.application.IOfficeApplication;
import ag.ion.bion.officelayer.application.OfficeApplicationException;
import ag.ion.bion.officelayer.application.OfficeApplicationRuntime;
import ag.ion.bion.officelayer.desktop.GlobalCommands;
import ag.ion.bion.officelayer.desktop.IFrame;
import ag.ion.bion.officelayer.document.DocumentDescriptor;
import ag.ion.bion.officelayer.document.IDocument;
import ag.ion.bion.officelayer.internal.application.ApplicationAssistant;

public class TestFrame 
{

    private final static String OPEN_OFFICE_ORG_PATH = "/usr/lib/libreoffice"; 
    
     private static TextEditor txtEditor;
     public static JTextPane tpHTML;
     
     
     
     private JPanel NOApanel;
     
      public static void main(String[] args)
        {
         
          JButton btnSave, btnLoad;
          btnSave = new JButton("Save");
          btnLoad = new JButton("Load");
          tpHTML = new JTextPane();
          
          btnSave.addActionListener(new ActionListener()
            {
              @Override
              public void actionPerformed(ActionEvent evt)
              {
                  tpHTML.setText(txtEditor.getText());
              }

            });
          
          btnLoad.addActionListener(new ActionListener()
            {
              @Override    
              public void actionPerformed(ActionEvent evt)
              {
                  txtEditor.setText(tpHTML.getText());
              }
            });
          
          GridLayout layout = new GridLayout();
           JPanel plnMain = new JPanel(layout);
          txtEditor = new TextEditor();
          //txtEditor.setPreferredSize(new Dimension(700, 400));
            // Erzeugung eines neuen Frames mit dem 
              // Titel "Beispiel JFrame " 
                
            
            
            
           
          
          JFrame meinFrame = new JFrame("Beispiel JFrame");
            meinFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
            meinFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            /* Wir setzen die Breite und die Höhe 
               unseres Fensters auf 200 Pixel */        
            //txtEditor.setSize(400,400);
            // Wir lassen unseren Frame anzeigen
            
            
            
            plnMain.add(txtEditor);
            plnMain.add(btnLoad);
            plnMain.add(btnSave);
            
            
            //tpHTML.setPreferredSize(new Dimension(700, 400));
            
            tpHTML.setBackground(Color.LIGHT_GRAY);
            plnMain.add(tpHTML);
            
            
            
            
            
            //InitOOFrame(meinFrame);
            
            meinFrame.add(plnMain);
            
            meinFrame.setVisible(true);
        }
    
    
      
        

}


TextEditor.java
Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
 
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;
import javax.swing.text.Element;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.StyledEditorKit.FontFamilyAction;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.MinimalHTMLWriter;


public class TextEditor extends JPanel implements ActionListener, ItemListener
{
      private static final long serialVersionUID = 2232612551746729177L;
      
      // Textpane zur Darstellung
      private JTextPane pane = null;
      //private JTextPane html_pane = null;
      
      // Unser Document
      private HTMLDocument doc = null;
      private EditorKit editorKit;
      
      String[] font;
      private StyledEditorKit.FontFamilyAction []actions;
      
      // Button um etwas fett zu markieren
      private JButton bold = null;
      // Button um etwas krusiv zu markieren
      private JButton italic = null;
      // Button um etwas zu unterstreichen
      private JButton underline = null;
      // Button um die Schriftfarbe zu ändern
      private JButton foreground = null;
      // Button um die Hintergrundfarbe zu ändern
      private JButton background = null;
      // Button um ein Bild einzufügen
      private JButton pic = null;
     
      // JComboBox mit allen verfügbaren Schriftarten
      private JComboBox fonts = null;
      // JComboBox mit unterschiedlichen Schriftgrößen
      private JComboBox size = null;
     
      // Toolbar für die Buttons und ComboBoxen
      private JToolBar bar = null;
     
      // JFileChooser um ggf. ein Bild auswählen zu können
      private JFileChooser imch = null;
     
      public TextEditor() {
     
        setLayout(new BorderLayout());
     
        // Anzeigebereich erzeugen
        this.doc = new HTMLDocument();
        this.pane = new JTextPane(this.doc);
        
        //  Debuger
        //this.html_pane = new JTextPane();
        //this.html_pane.setPreferredSize(new Dimension(400,300));
        
        
        pane.setEditorKit(new HTMLEditorKit());
        pane.setContentType( "text/html" );
        editorKit = pane.getEditorKit();
        
        // Tools initialisieren
        this.bold = new JButton("F");
        this.italic = new JButton("I");
        this.underline = new JButton("U");
        this.foreground = new JButton("SF");
        this.background = new JButton("HF");
        this.pic = new JButton("Bild");
     
        this.fonts = new JComboBox();
        this.size = new JComboBox();
     
        // restliche Komponenten initialisieren
        this.bar = new JToolBar();
     
        this.imch = new JFileChooser();
     
        // Einen FileFilter für die Bildauswahl setzen
        // es dürfen nur jpg und png Bilder eingefügt werden
        this.imch.setFileFilter(new FileFilter() {
     
          public boolean accept(File f) {
     
            if (f.isDirectory()) {
              return true;
            }
            if (f.getAbsolutePath().toLowerCase().endsWith(".png")) {
              return true;
            }
            if (f.getAbsolutePath().toLowerCase().endsWith(".jpg")) {
              return true;
            }
            return f.getAbsolutePath().toLowerCase().endsWith(".jpeg");
          }
     
          public String getDescription() {
            return "Image (*.jpg, *.jpeg, *.png)";
          }
        });
     
        // Verschiedene Schriftgrößen initialisieren
        for (int i = 8; i < 30; i += 2) {
          this.size.addItem(i);
        }
     
        // Alle verfügbaren Schriftarten auslesen und in der JComboBox anzeigen
        font = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
     
        //actions = new FontFamilyAction[fonts.length];
       /*
        for (int i = 0; i < font.length; i++) {
          this.fonts.addItem(font[i]);
          actions[i] = new StyledEditorKit.FontFamilyAction(font[i], font[i]);
        }
         */
        
        
        // GUI zusammenbauen
        add(this.bar, BorderLayout.NORTH);
        add(this.pane, BorderLayout.CENTER);
        //add(this.html_pane, BorderLayout.SOUTH);
      //this.html_pane.setText("fdgdfg");
     
        this.bar.add(this.bold);
        this.bar.add(this.italic);
        this.bar.add(this.underline);
        this.bar.add(this.fonts);
        this.bar.add(this.size);
        this.bar.add(this.foreground);
        this.bar.add(this.background);
        this.bar.add(this.pic);
     
        // Listener an die Tools hängen
        this.pane.addKeyListener(new KeyListener() {

            @Override
            public void keyTyped(KeyEvent arg0) 
            {

            }

            @Override
            public void keyReleased(KeyEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void keyPressed(KeyEvent arg0) {
                //html_pane.setText(getText());

            }
        });
        
        this.bold.addActionListener(new StyledEditorKit.BoldAction());
        this.italic.addActionListener(new StyledEditorKit.ItalicAction());
        this.underline.addActionListener(new StyledEditorKit.UnderlineAction());
        //this.foreground.addActionListener(this);
        //this.background.addActionListener(this);
        //this.pic.addActionListener(this);
     
        //this.fonts.addItemListener(this);
        //this.size.addItemListener(this);
      }
     
      
      public String getText()
      {
          
          try {
    
    
            HTMLDocument html_doc = (HTMLDocument) pane.getDocument();
                
            String str;
            
            
            /*
            Element firstLine = html_doc.getDefaultRootElement().getElement(0);
            
            html_doc.removeElement(firstLine);
             firstLine = null;
            
            */
            
              StringWriter writer = new StringWriter();
              MinimalHTMLWriter htmlWriter = new HeaderFooterHTMLWriter(writer, html_doc);
              htmlWriter.write();
              str =  writer.getBuffer().toString();            
              
              
              //str = str.replaceAll("\n", "<br/>");
              //str = str.replaceAll("\r\n", "<br>");
            /*
            ByteArrayOutputStream out =  new ByteArrayOutputStream();
            editorKit.write(out, html_doc, 0, html_doc.getLength());
            */
              
            System.out.println("GetText" + str);
            
            return str ;//out.toString();
        } catch (BadLocationException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
      }
      
      public void setText(String text)
      {
          try
            {
                System.out.println("SetText" + text);
                 
              //((AbstractDocument) pane.getDocument()).setDocumentFilter(new HtmlLineBreakDocumentFilter());
            //StyledDocument doc = (HTMLDocument) editorKit.createDefaultDocument();    
                //HTMLDocument doc = (HTMLDocument) editorKit.createDefaultDocument();
                HTMLDocument xdoc =  new HTMLDocument();
                pane.setText("");
                
                
                //text = text.replaceAll("\r\n", "\n");
                //text = text.replaceAll( "<br>", "&nbsp;");
                Reader stringReader = new StringReader(text);
            
            editorKit.read(stringReader, xdoc, 0);
            pane.setDocument(xdoc);
                
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (BadLocationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  
      }
      
      public void actionPerformed(ActionEvent evt) 
      {
     
        
          
        // Start und End Position der Selektion auslesen
        int start = this.pane.getSelectionStart();
        int end = this.pane.getSelectionEnd();
        // Falls keine sinnvolle Selektion => kompletten Text bearbeiten
        if (start >= end) {
          start = 0;
          end = this.pane.getText().length();
        }
      
        /*
        // Fett setzen
        if (evt.getSource() == this.bold) {
          // Falls das erste, selektierte Zeichen bereits fett dargestellt
          // wird, die Fett-Formatierung aufheben, ansonsten den selektierten
          // Bereich fett darstellen
          this.doc.setBold(start, end, !this.doc.isBold(start));
        }
        // Kursiv setzen
        else if (evt.getSource() == this.italic) {
          // siehe "Fett setzen"
          this.doc.setItalic(start, end, !this.doc.isItalic(start));
        }
        // Unterstreichen
        else if (evt.getSource() == this.underline) {
          // siehe "Fett setzen"
          this.doc.setUnderline(start, end, !this.doc.isUnderline(start));
        }
        
        */
        
        
        // Schriftfarbe verändern
        else if (evt.getSource() == this.foreground) {
            JColorChooser choser = new JColorChooser();
            
          Color col = choser.showDialog(this, "Schriftfarbe auswählen", Color.BLACK);
          
          if (col != null) {
              StyledEditorKit.ForegroundAction customColorAction = new StyledEditorKit.ForegroundAction("CustomColor", col);
               customColorAction.actionPerformed(evt);
              //this.doc.setForeground(start, end, col);
          }
          
         
          
        }
        // Hintergrundfarbe verändern
        else if (evt.getSource() == this.background) {
          Color col = JColorChooser.showDialog(this, "Hintergrundfarbe auswählen", Color.WHITE);
          if (col != null) {
              StyledEditorKit.ForegroundAction customColorAction = new StyledEditorKit.ForegroundAction("CustomColor", col);
              customColorAction.actionPerformed(evt);
              //this.doc.setBackground(start, end, col);
          }
        }
        // Bild einfügen
        else if (evt.getSource() == this.pic) {
          int retval = this.imch.showOpenDialog(this);
          if (retval == JFileChooser.APPROVE_OPTION) {
            this.pane.replaceSelection("");
          }
        }
      }
     
      public void itemStateChanged(ItemEvent evt) {
     
        // Nur reagieren, falls etwas neues selektiert wurde
        if (evt.getStateChange() == ItemEvent.SELECTED) {
          // Start und End Position der Selektion auslesen
          int start = this.pane.getSelectionStart();
          int end = this.pane.getSelectionEnd();
          // Falls keine sinnvolle Selektion => kompletten Text bearbeiten
          if (start >= end) {
            start = 0;
            end = this.pane.getText().length();
          }
          // Schriftart setzen
          if (evt.getSource() == this.fonts) {
              
              
              for (int i = 0; i < actions.length; i++)
              {
                  if (font[i].equals(this.fonts.getSelectedItem().toString()))
                  {
                      StyledEditorKit.FontFamilyAction FontAction = new StyledEditorKit.FontFamilyAction("Font", this.fonts.getSelectedItem().toString());
                      //FontAction.actionPerformed(actions[i]);
                      
                      break;
                  }
              }
              
            //this.doc.setFont(start, end, this.fonts.getSelectedItem().toString());
          
             
          }
          // Schriftgröße setzen
          else if (evt.getSource() == this.size) {
            //this.doc.setFontSize(start, end, Integer.parseInt(this.size.getSelectedItem().toString()));
          }
        }
      }


    
     
      
}



HeaderFooterHTMLWriter.java
Code:
package eu.campocreativo.text_editor;

import java.io.IOException;
import java.io.Writer;

import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.StyledDocument;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.MinimalHTMLWriter;

/**
 * This class produce the HTML code from the formatted text in the Editor Pane.
 * The default writer produce too much code, including html, head, style and body tags.
 */
class HeaderFooterHTMLWriter extends MinimalHTMLWriter
{
   public HeaderFooterHTMLWriter(Writer w, HTMLDocument doc)
   {
      super(w, doc);
      //Do not let the writer to produce extra newline characters.
      setLineSeparator("\n");
      //Do not try to wrap the code.
      setCanWrapLines(false);
   }

   //Do no need header
   protected void writeHeader() throws IOException
   {
   }

   //Only the span tags are needed.
   protected void writeStartTag(String tag) throws IOException
   {
      //replace span tag with font, so that it can appear in table tags
      if (tag.startsWith("<span"))
         super.writeStartTag("<p" + tag.substring(5));
   }

   protected void writeEndTag(String endTag) throws IOException
   {
      if (endTag.equals("</span>"))
         super.writeEndTag("</p>");
   }

   //Replace new lines inserted by the user with their corresponding html tag
   protected String getText(Element elem) throws BadLocationException
   {
      
      String strValue = super.getText(elem);
      
      //System.out.println(strValue + " -> " + elem.getEndOffset());
      /*
      if(elem.getEndOffset() == 1)  { 
         
          strValue = strValue.replaceAll("\n", "");
      }
      else
      {
          */
            //strValue = strValue.trim();
          strValue = strValue.replaceAll("\n", "<br>");
          //strValue = strValue.replaceAll(" ", "");
      //}
      return strValue;
   }
   
  
}




Ich wäre euch wirklich sehr verbunden wenn ihr eine Idee habt wie man das eigendlich bekannte Problem mit dem Withespace <br> ich hänge bereits 5 Wochen fest und komme mit meinem Projekt nicht vorran


lg Andreas
 

Ähnliche Java Themen

Neue Themen


Oben