Texto Justificado em JTextPane! Como?[RESOLVIDO]

Ja procurei aqui no forum, achei algunes tópicos mas ate agora nao consegui justificar um texto em um JTextPane!! ja tentei usar o style, mas to me debatendo aqui e nao consuigo!! alguem tem um exemplo de como usar o JUSTIFIED, na pratica mesmo, funcionando!!!

Bingoooo… consegui encontrar a solução para a justificação do Texto em um JTextPane, o problema é que ALIGN_JUSTIFIED é um bug do java: http://bugs.sun.com/bugdatabase/view_bug.do;:YfiG?bug_id=4263904

mas encontrei isso aqui oh:


package justifica;
 
import javax.swing.text.*;
import java.awt.*;
import javax.swing.*;
 
public class AdvancedParagraphView extends ParagraphView {
 
  public AdvancedParagraphView(Element elem) {
    super(elem);
 
    strategy = new AdvancedFlowStrategy();
  }
 
  protected View createRow() {
    Element elem = getElement();
    return new AdvancedRow(elem);
  }
 
  protected static int getSpaceCount(String content) {
    int result = 0;
    int index = content.indexOf(' ');
    while (index >= 0) {
      result++;
      index = content.indexOf(' ', index + 1);
    }
    return result;
  }
 
  protected static int[] getSpaceIndexes(String content, int shift) {
    int cnt = getSpaceCount(content);
    int[] result = new int[cnt];
    int counter = 0;
    int index = content.indexOf(' ');
    while (index >= 0) {
      result[counter] = index + shift;
      counter++;
      index = content.indexOf(' ', index + 1);
    }
    return result;
  }
 
  static class AdvancedFlowStrategy
      extends FlowStrategy {
    public void layout(FlowView fv) {
      super.layout(fv);
      AttributeSet attr = fv.getElement().getAttributes();
      float lineSpacing = StyleConstants.getLineSpacing(attr);
      boolean justifiedAlignment = (StyleConstants.getAlignment(attr) ==
                                    StyleConstants.ALIGN_JUSTIFIED);
      if (! (justifiedAlignment || (lineSpacing > 1))) {
        return;
      }
 
      int cnt = fv.getViewCount();
      for (int i = 0; i < cnt - 1; i++) {
        AdvancedRow row = (AdvancedRow) fv.getView(i);
        if (lineSpacing > 1) {
          float height = row.getMinimumSpan(View.Y_AXIS);
          float addition = (height * lineSpacing) - height;
          if (addition > 0) {
            row.setInsets(row.getTopInset(), row.getLeftInset(),
                          (short) addition, row.getRightInset());
          }
        }
 
        if (justifiedAlignment) {
          restructureRow(row, i);
          row.setRowNumber(i + 1);
        }
      }
    }
 
    protected void restructureRow(View row, int rowNum) {
      int rowStartOffset = row.getStartOffset();
      int rowEndOffset = row.getEndOffset();
      String rowContent = "";
      try {
        rowContent = row.getDocument().getText(rowStartOffset,
                                               rowEndOffset - rowStartOffset);
        if (rowNum == 0) {
          int index = 0;
          while (rowContent.charAt(0) == ' ') {
            rowContent = rowContent.substring(1);
            if (rowContent.length() == 0)
              break;
          }
        }
      }
      catch (Exception e) {
        e.printStackTrace();
      }
      int rowSpaceCount = getSpaceCount(rowContent);
      if (rowSpaceCount < 1)
        return;
      int[] rowSpaceIndexes = getSpaceIndexes(rowContent, row.getStartOffset());
      int currentSpaceIndex = 0;
 
      for (int i = 0; i < row.getViewCount(); i++) {
        View child = row.getView(i);
        if ( (child.getStartOffset() < rowSpaceIndexes[currentSpaceIndex]) &&
            (child.getEndOffset() > rowSpaceIndexes[currentSpaceIndex])) {
//split view
          View first = child.createFragment(child.getStartOffset(),
                                            rowSpaceIndexes[currentSpaceIndex]);
          View second = child.createFragment(rowSpaceIndexes[currentSpaceIndex],
                                             child.getEndOffset());
          View[] repl = new View[2];
          repl[0] = first;
          repl[1] = second;
 
          row.replace(i, 1, repl);
          currentSpaceIndex++;
          if (currentSpaceIndex >= rowSpaceIndexes.length)
            break;
        }
      }
      int childCnt = row.getViewCount();
    }
 
  }
 
  class AdvancedRow
      extends BoxView {
 
    private int rowNumber = 0;
 
    AdvancedRow(Element elem) {
      super(elem, View.X_AXIS);
    }
 
    protected void loadChildren(ViewFactory f) {
    }
 
    public AttributeSet getAttributes() {
      View p = getParent();
      return (p != null) ? p.getAttributes() : null;
    }
 
    public float getAlignment(int axis) {
      if (axis == View.X_AXIS) {
        AttributeSet attr = getAttributes();
        int justification = StyleConstants.getAlignment(attr);
        switch (justification) {
          case StyleConstants.ALIGN_LEFT:
          case StyleConstants.ALIGN_JUSTIFIED:
            return 0;
          case StyleConstants.ALIGN_RIGHT:
            return 1;
          case StyleConstants.ALIGN_CENTER:
            return 0.5f;
        }
      }
      return super.getAlignment(axis);
    }
 
    public Shape modelToView(int pos, Shape a, Position.Bias b) throws
        BadLocationException {
      Rectangle r = a.getBounds();
      View v = getViewAtPosition(pos, r);
      if ( (v != null) && (!v.getElement().isLeaf())) {
// Don't adjust the height if the view represents a branch.
        return super.modelToView(pos, a, b);
      }
      r = a.getBounds();
      int height = r.height;
      int y = r.y;
      Shape loc = super.modelToView(pos, a, b);
      r = loc.getBounds();
      r.height = height;
      r.y = y;
      return r;
    }
 
    public int getStartOffset() {
      int offs = Integer.MAX_VALUE;
      int n = getViewCount();
      for (int i = 0; i < n; i++) {
        View v = getView(i);
        offs = Math.min(offs, v.getStartOffset());
      }
      return offs;
    }
 
    public int getEndOffset() {
      int offs = 0;
      int n = getViewCount();
      for (int i = 0; i < n; i++) {
        View v = getView(i);
        offs = Math.max(offs, v.getEndOffset());
      }
      return offs;
    }
 
    protected void layoutMinorAxis(int targetSpan, int axis, int[] offsets,
                                   int[] spans) {
      baselineLayout(targetSpan, axis, offsets, spans);
    }
 
    protected SizeRequirements calculateMinorAxisRequirements(int axis,
        SizeRequirements r) {
      return baselineRequirements(axis, r);
    }
 
    protected int getViewIndexAtPosition(int pos) {
// This is expensive, but are views are not necessarily layed
// out in model order.
      if (pos < getStartOffset() || pos >= getEndOffset())
        return -1;
      for (int counter = getViewCount() - 1; counter >= 0; counter--) {
        View v = getView(counter);
        if (pos >= v.getStartOffset() &&
            pos < v.getEndOffset()) {
          return counter;
        }
      }
      return -1;
    }
 
    public short getTopInset() {
      return super.getTopInset();
    }
 
    public short getLeftInset() {
      return super.getLeftInset();
    }
 
    public short getRightInset() {
      return super.getRightInset();
    }
 
    public void setInsets(short topInset, short leftInset, short bottomInset,
                          short rightInset) {
      super.setInsets(topInset, leftInset, bottomInset, rightInset);
    }
 
    protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets,
                                   int[] spans) {
      super.layoutMajorAxis(targetSpan, axis, offsets, spans);
      AttributeSet attr = getAttributes();
      if ( (StyleConstants.getAlignment(attr) != StyleConstants.ALIGN_JUSTIFIED) &&
          (axis != View.X_AXIS)) {
        return;
      }
      int cnt = offsets.length;
 
      int span = 0;
      for (int i = 0; i < cnt; i++) {
        span += spans[i];
      }
      if (getRowNumber() == 0)
        return;
      int startOffset = getStartOffset();
      int len = getEndOffset() - startOffset;
      String context = "";
      try {
        context = getElement().getDocument().getText(startOffset, len);
      }
      catch (Exception e) {
        e.printStackTrace();
      }
      int spaceCount = getSpaceCount(context) - 1;
 
      int pixelsToAdd = targetSpan - span;
 
      if (this.getRowNumber() == 1) {
        int firstLineIndent = (int) StyleConstants.getFirstLineIndent(
            getAttributes());
        pixelsToAdd -= firstLineIndent;
      }
 
      int[] spaces = getSpaces(pixelsToAdd, spaceCount);
      int j = 0;
      int shift = 0;
      for (int i = 1; i < cnt; i++) {
        LabelView v = (LabelView) getView(i);
        offsets[i] += shift;
        if ( (isContainSpace(v)) && (i != cnt - 1)) {
          offsets[i] += spaces[j];
          spans[i - 1] += spaces[j];
          shift += spaces[j];
          j++;
        }
      }
    }
 
    protected int[] getSpaces(int space, int cnt) {
      int[] result = new int[cnt];
      if (cnt == 0)
        return result;
      int base = space / cnt;
      int rst = space % cnt;
 
      for (int i = 0; i < cnt; i++) {
        result[i] = base;
        if (rst > 0) {
          result[i]++;
          rst--;
        }
      }
 
      return result;
    }
 
    public float getMinimumSpan(int axis) {
      if (axis == View.X_AXIS) {
        AttributeSet attr = getAttributes();
        if (StyleConstants.getAlignment(attr) != StyleConstants.ALIGN_JUSTIFIED) {
          return super.getMinimumSpan(axis);
        }
        else {
          return this.getParent().getMinimumSpan(axis);
        }
      }
      else {
        return super.getMinimumSpan(axis);
      }
    }
 
    public float getMaximumSpan(int axis) {
      if (axis == View.X_AXIS) {
        AttributeSet attr = getAttributes();
        if (StyleConstants.getAlignment(attr) != StyleConstants.ALIGN_JUSTIFIED) {
          return super.getMaximumSpan(axis);
        }
        else {
          return this.getParent().getMaximumSpan(axis);
        }
      }
      else {
        return super.getMaximumSpan(axis);
      }
    }
 
    public float getPreferredSpan(int axis) {
      if (axis == View.X_AXIS) {
        AttributeSet attr = getAttributes();
        if (StyleConstants.getAlignment(attr) != StyleConstants.ALIGN_JUSTIFIED) {
          return super.getPreferredSpan(axis);
        }
        else {
          return this.getParent().getPreferredSpan(axis);
        }
      }
      else {
        return super.getPreferredSpan(axis);
      }
    }
 
    public void setRowNumber(int value) {
      rowNumber = value;
    }
 
    public int getRowNumber() {
      return rowNumber;
    }
  }
 
  public int getFlowSpan(int index) {
    int span = super.getFlowSpan(index);
    if (index == 0) {
      int firstLineIdent = (int) StyleConstants.getFirstLineIndent(this.
          getAttributes());
      span -= firstLineIdent;
    }
    return span;
  }
 
  protected void layoutMinorAxis(int targetSpan, int axis, int[] offsets,
                                 int[] spans) {
    super.layoutMinorAxis(targetSpan, axis, offsets, spans);
    int firstLineIdent = (int) StyleConstants.getFirstLineIndent(this.
        getAttributes());
    offsets[0] += firstLineIdent;
  }
 
  protected static boolean isContainSpace(View v) {
    int startOffset = v.getStartOffset();
    int len = v.getEndOffset() - startOffset;
    try {
      String text = v.getDocument().getText(startOffset, len);
      if (text.indexOf(' ') >= 0)
        return true;
      else
        return false;
    }
    catch (Exception ex) {
      return false;
    }
 
  }
}

/*
 * FixedStyledEditorKit.java
 *
 * Created on 21 de Julho de 2005, 10:54
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */

package justifica;
import javax.swing.text.*;
 
public class FixedStyledEditorKit extends StyledEditorKit {
 
  public ViewFactory getViewFactory() {
 
    return new FixedStyledViewFactory();
 
  }
 
}
/*
 * FixedStyledViewFactory.java
 *
 * Created on 21 de Julho de 2005, 10:55
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */

package justifica;

import javax.swing.text.*;
 
public class FixedStyledViewFactory implements ViewFactory {
 
  public View create(Element elem) {
    String kind = elem.getName();
    if (kind != null) {
      if (kind.equals(AbstractDocument.ContentElementName)) {
        return new LabelView(elem);
      }
      else if (kind.equals(AbstractDocument.ParagraphElementName)) {
 
// return new ParagraphView(elem);
        return new AdvancedParagraphView(elem);
      }
      else if (kind.equals(AbstractDocument.SectionElementName)) {
        return new BoxView(elem, View.Y_AXIS);
      }
      else if (kind.equals(StyleConstants.ComponentElementName)) {
        return new ComponentView(elem);
      }
      else if (kind.equals(StyleConstants.IconElementName)) {
        return new IconView(elem);
      }
    }
 
// default to text display
    return new LabelView(elem);
  }
}
/*
 * Main.java
 *
 * Created on 21 de Julho de 2005, 10:49
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */

package justifica;

/**
 *
 * @author Administrador
 */
import javax.swing.text.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class Main extends JFrame
{
  private JTextPane myTextPane;
  private SimpleAttributeSet sas;
  private StyledDocument theDocument;

  public Main()
  {
    super();

    setSize( 500, 500);
    getContentPane().setLayout( new GridLayout( 1, 2));

    myTextPane = new JTextPane();
    myTextPane.setSize( 250, 250);
    myTextPane.setEditorKit(new FixedStyledEditorKit());//aqui...
    getContentPane().add( myTextPane);
    myTextPane.setText( "A long line of text for testing alignment");

    sas = new SimpleAttributeSet();

    JButton leftAlignButton = new JButton( "left");
    JButton rightAlignButton = new JButton( "right");
    JButton centreButton = new JButton( "centered");
    JButton justifyButton = new JButton( "justified");

    JPanel buttonPanel = new JPanel();

    leftAlignButton.addActionListener( new ActionListener() {
      public void actionPerformed( ActionEvent e)
      {
        StyleConstants.setAlignment( sas, StyleConstants.ALIGN_LEFT);
        myTextPane.setParagraphAttributes( sas, false);

        myTextPane.repaint();             
      }
    });

    rightAlignButton.addActionListener( new ActionListener() {
      public void actionPerformed( ActionEvent e)
      {
        StyleConstants.setAlignment( sas, StyleConstants.ALIGN_RIGHT);
        myTextPane.setParagraphAttributes( sas, false);

        myTextPane.repaint();
      }
    });

    centreButton.addActionListener( new ActionListener() {
      public void actionPerformed( ActionEvent e)
      {
        StyleConstants.setAlignment( sas, StyleConstants.ALIGN_CENTER);
        myTextPane.setParagraphAttributes( sas, false);

        myTextPane.repaint();      }
    });

    justifyButton.addActionListener( new ActionListener() {
      public void actionPerformed( ActionEvent e)
      {
        StyleConstants.setAlignment( sas, StyleConstants.ALIGN_JUSTIFIED);
        myTextPane.setParagraphAttributes( sas, false);

        myTextPane.repaint();
      }
    });

    buttonPanel.add( leftAlignButton);
    buttonPanel.add( centreButton);
    buttonPanel.add( rightAlignButton);
    buttonPanel.add( justifyButton);

    getContentPane().add( buttonPanel);
    
    setSize(300, 300);
    setVisible(true);
  }

  public static void main( String args[])
  {
    Main myFrame = new Main();
    myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
}

Agora ta ai pra quem tiver precisando!!!