# Formatierungen von JTextPane in xml umwandeln



## MScalli (17. August 2008)

Hi Leutz.

Ich habe ein ziemliches Problem und weiss nicht genau wie ich da ran gehen soll.

Ich muss mittels JasperReports einen Bericht erstellen und in diesem Bericht soll als Kommentar ein Formatierter Text eingefügt werden(es können in dem Text verschiedene Formatierungen vorhanden sein.. fett, kursiv, verschiedene Schriftarten- und -grössen.

wenn ich den Text in xml tags packe geht das auch. z.B. so..

<style isItalic="true" pdfFontName="Helvetica-Oblique">kursiv</style>
<style isBold="true" pdfFontName="Helvetica-Bold">fett</style>
usw.

geht das auch irgendwie anderst Also ich habe bei JasperReports keine andere möglichkeit gefunden.. aber vielleicht weiss ja jemand ne andere lösung.

Ich hätte ein JTextPane genommen, die Formatierung ausgelesen, den text mit den entsprechenden xml tags versehen und in der Datenbank/Textdatei als xml-Text gespeichert.

Hier mal mein Ansatz.. (noch ne Frage zum Code.. muss ich da jetzt ne schleife machen und JEDE Schriftgrösse bzw. Schriftart abfragen!)

Klasse EditorDocument

```
import java.awt.Color;

import javax.swing.ImageIcon;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Element;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

public class EditorDocument extends DefaultStyledDocument {

   private static final long serialVersionUID = 1L;
   
   public void setBold(int startPosition, int endPosition) {

      for (int i = startPosition; i < endPosition; i++) {
         setBold(getSimpleAttributeSet(i), i);
      }
   }

   public void setItalic(int startPosition, int endPosition) {

      for (int i = startPosition; i < endPosition; i++) {
         setItalic(getSimpleAttributeSet(i), i);
      }
   }

   public void setUnderline(int startPosition, int endPosition) {

      for (int i = startPosition; i < endPosition; i++) {
         setUnderline(getSimpleAttributeSet(i), i);
      }
   }

   public void setFont(int startPosition, int endPosition, String font) {

      for (int i = startPosition; i < endPosition; i++) {
         setFont(getSimpleAttributeSet(i), i, font);
      }
   }

   public void setFontSize(int startPosition, int endPosition, int size) {

      for (int i = startPosition; i < endPosition; i++) {
         setSize(getSimpleAttributeSet(i), i, size);
      }
   }

   public void setForeground(int startPosition, int endPosition, Color col) {

      for (int i = startPosition; i < endPosition; i++) {
         setForeground(getSimpleAttributeSet(i), i, col);
      }
   }

   public void setBackground(int startPosition, int endPosition, Color col) {

      for (int i = startPosition; i < endPosition; i++) {
         setBackground(getSimpleAttributeSet(i), i, col);
      }
   }

   public void setIcon(int pos, ImageIcon ico) throws BadLocationException {

      Style style = getStyle("default");
      StyleConstants.setIcon(style, ico);
      insertString(pos, " ", style);
   }

   private void setItalic(SimpleAttributeSet sas, int pos) {

      if (StyleConstants.isItalic(sas)) {
         StyleConstants.setItalic(sas, false);
      }
      else {
         StyleConstants.setItalic(sas, true);
      }
      setCharacterAttributes(pos, 1, sas, true);
   }

   private void setBold(SimpleAttributeSet sas, int pos) {

      if (StyleConstants.isBold(sas)) {
         StyleConstants.setBold(sas, false);
      }
      else {
         StyleConstants.setBold(sas, true);
      }
      setCharacterAttributes(pos, 1, sas, true);
   }

   private void setUnderline(SimpleAttributeSet sas, int pos) {

      if (StyleConstants.isUnderline(sas)) {
         StyleConstants.setUnderline(sas, false);
      }
      else {
         StyleConstants.setUnderline(sas, true);
      }
      setCharacterAttributes(pos, 1, sas, true);
   }

   private void setFont(SimpleAttributeSet sas, int pos, String font) {

      StyleConstants.setFontFamily(sas, font);
      setCharacterAttributes(pos, 1, sas, true);
   }

   private void setSize(SimpleAttributeSet sas, int pos, int size) {

      StyleConstants.setFontSize(sas, size);
      setCharacterAttributes(pos, 1, sas, true);
   }

   private void setForeground(SimpleAttributeSet sas, int pos, Color col) {

      StyleConstants.setForeground(sas, col);
      setCharacterAttributes(pos, 1, sas, true);
   }

   private void setBackground(SimpleAttributeSet sas, int pos, Color col) {

      StyleConstants.setBackground(sas, col);
      setCharacterAttributes(pos, 1, sas, true);
   }

   public SimpleAttributeSet getSimpleAttributeSet(int pos) {

      Element ele = getCharacterElement(pos);
      AttributeSet as = ele.getAttributes();
      SimpleAttributeSet sas = new SimpleAttributeSet(as);
      return sas;
   }

   public EditorDocument() {
      super();
   }

   public EditorDocument(Content arg0, StyleContext arg1) {
      super(arg0, arg1);
   }

   public EditorDocument(StyleContext arg0) {
      super(arg0);
   }
}
```


Klasse EditorComponent

```
import java.awt.BorderLayout;
import java.awt.Color;
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.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
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.BadLocationException;
import javax.swing.text.EditorKit;
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;

public class EditorComponent extends JPanel implements ActionListener, ItemListener {

   private static final long serialVersionUID = 1L;

   private JTextPane pane = null;
   private EditorDocument doc = null;
   File file = new File("c:\\temp\\Test.htm");
   
   private JButton bold = null;
   private JButton italic = null;
   private JButton underline = null;
   private JButton foreground = null;
   private JButton background = null;
   private JButton save = null;

   private JComboBox fonts = null;
   private JComboBox size = null;

   private JToolBar bar = null;

   private JFileChooser imch = null;

   public EditorComponent() {

      setLayout(new BorderLayout());

      doc = new EditorDocument();
      pane = new JTextPane(doc);
      
      //pane.setContentType("text/xml");

      bold = new JButton("F");
      italic = new JButton("I");
      underline = new JButton("U");
      foreground = new JButton("SF");
      background = new JButton("HF");
      save = new JButton("save");

      fonts = new JComboBox();
      size = new JComboBox();

      bar = new JToolBar();

      imch = new JFileChooser();

      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)";
         }
      });

      for (int i = 8; i < 30; i+= 2) {
         size.addItem(i);
      }

      String[] font = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();

      for (int i = 0; i < font.length; i++) {
         fonts.addItem(font[i]);
      }

      add(pane);
      add(bar, BorderLayout.NORTH);

      bar.add(bold);
      bar.add(italic);
      bar.add(underline);
      bar.add(fonts);
      bar.add(size);
      bar.add(foreground);
      bar.add(background);
      bar.add(save);

      bold.addActionListener(this);
      italic.addActionListener(this);
      underline.addActionListener(this);
      foreground.addActionListener(this);
      background.addActionListener(this);
      save.addActionListener(this);

      fonts.addItemListener(this);
      size.addItemListener(this);
   }

   public void actionPerformed(ActionEvent evt) {

      int start = pane.getSelectionStart();
      int end = pane.getSelectionEnd();
      if (start >= end) {
         start = 0;
         end = pane.getText().length();
      }
      if (evt.getSource() == bold) {
         doc.setBold(start, end);
      }
      else if (evt.getSource() == italic) {
         doc.setItalic(start, end);
      }
      else if (evt.getSource() == underline) {
         doc.setUnderline(start, end);
      }
      else if (evt.getSource() == foreground) {
         Color col = JColorChooser.showDialog(this, "Schriftfarbe auswählen", Color.BLACK);
         if (col != null) {
            doc.setForeground(start, end, col);
         }
      }
      else if (evt.getSource() == background) {
         Color col = JColorChooser.showDialog(this, "Hintergrundfarbe auswählen", Color.WHITE);
         if (col != null) {
            doc.setBackground(start, end, col);
         }
      }
      else if (evt.getSource() == save) {
        System.out.println("Button Save");
        
        printFormatOfSelectedText();
        
   /*     try {
      System.out.println(doc.getText(0, doc.getLength()));
      MyFile.createFile("c:\\temp", "Formatierung.txt", doc.getText(0, doc.getLength()));
    } catch (BadLocationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    */
      }
   }

   public void itemStateChanged(ItemEvent evt) {

      if (evt.getStateChange() == ItemEvent.SELECTED) {
         int start = pane.getSelectionStart();
         int end = pane.getSelectionEnd();
         if (start >= end) {
            start = 0;
            end = pane.getText().length();
         }
         if (evt.getSource() == fonts) {
            doc.setFont(start, end, fonts.getSelectedItem().toString());
         }
         else if (evt.getSource() == size) {
            doc.setFontSize(start, end, Integer.parseInt(size.getSelectedItem().toString()));
         }
      }
   }

   public static void main(String[] args) {

      JFrame frame = new JFrame();
      frame.add(new JScrollPane(new EditorComponent()));
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(400, 600);
      frame.setVisible(true);
   }
   
   private void printFormatOfSelectedText() {
      System.out.println("printFormatOfSelectedText");
      
      

      final int startPos  = 0;
      final int endPos    = doc.getLength();

      final MutableAttributeSet setBold = new SimpleAttributeSet();
      StyleConstants.setBold(setBold, true);
      
      final MutableAttributeSet setItalic = new SimpleAttributeSet();
      StyleConstants.setItalic(setItalic, true);

      final MutableAttributeSet setUnderline = new SimpleAttributeSet();
      StyleConstants.setUnderline(setUnderline, true);
      
        for (int i = startPos; i < endPos; i++) {
          final Element element = doc.getCharacterElement(i);
          
          if (element.getAttributes().containsAttributes(setItalic)) {
        try {
        System.out.println(doc.getText(i, 1) + " is italic!");
      } catch (BadLocationException e) {
        e.printStackTrace();
      }
      }
          if (element.getAttributes().containsAttributes(setBold)) {
            try {
        System.out.println(doc.getText(i, 1) + " is bold!");
      } catch (BadLocationException e) {
        e.printStackTrace();
      }
          }
          if (element.getAttributes().containsAttributes(setUnderline)) {
              try {
          System.out.println(doc.getText(i, 1) + " is Underline!");
        } catch (BadLocationException e) {
          e.printStackTrace();
        }
            }
        }
    }
}
```

wäre echt dankbar für nen kleinen schubs in die richtige richtung 
(den grund Editor hab ich aus dem Netz)

gruss
MScalli


----------

