user3610008
user3610008

Reputation: 79

Center alignment of a word in JTextPane

I have a text that needs to be formatted, and the first word of the text needs to be bold with large font and centered.

To do this formatting i am using the solution from TextSamplerDemo.java in the oracle tutorial of the JTextComponents, the solution works rather well but the centering doesn't work!

Now i know that there are answers already in Stack Overflow about aligning text in a JTextPane and on other forums but they are all solutions about aligning all the text, and there are non about aligning one word or a part of the text.

Again, the font, the size and the "boldness" (don't know the correct term but you understand what i mean ;-p ) they all work, but the centering doesn't.

Here is the code that i am using to set up the JTextPane:

import java.awt.BorderLayout;
import java.text.SimpleDateFormat;
import java.util.Locale;
import javax.swing.JInternalFrame;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import domain.Fiche_Employe;
import persistance.Lecture_Fiche;

public class Attestation extends JInternalFrame {

/**
 * Launch the application.
 */

/**
 * 
 */
private static final long serialVersionUID = 1L;
JTextPane attest;


/**
 * Create the frame.
 */
public Attestation(String mat) {
            //This a DataBase connection and data fetching
    Fiche_Employe fiche=new Fiche_Employe();
    Lecture_Fiche f=new Lecture_Fiche(mat, fiche);
    f.lire_fiche();

            //Frame Creation
            setBounds(100, 100, 450, 300);
    setVisible(true);   

            //Creation of the JtextPane 
    attest=createTextPane(fiche.getSociete(), fiche.getSexe(), fiche.getnom(), String.valueOf(fiche.getcnss()), new SimpleDateFormat("dd MMMMMMMMM yyyy", Locale.FRANCE).format(fiche.getDateEntree()), fiche.getQualification(),fiche.getCategorie(), fiche.getEchelon(), fiche.getSituationProf());
    getContentPane().add(attest, BorderLayout.CENTER); 



}

private JTextPane createTextPane(String code, String sexe, String nomPrenom, String cnss, String dateEntree, 
        String Qualif, String Categ, String ech, String SituatProf) {

    String civilite = null;
    String Societe;
    if (sexe.replaceAll("\\s+$", "").toLowerCase().equals("m"))
        civilite="Monsieur ";
    else if (sexe.replaceAll("\\s+$", "").toLowerCase().equals("f"))
        civilite="Madame ";
    if (code.replaceAll("\\s+$", "")=="200")
        Societe="text";
    else 
        Societe="text";


    String newline = "\n";
    String[] initString =
            { "ATTESTATION",            
            newline+newline+newline+"Nous soussignés, "+Societe+" attestons que Monsieur  ",                                   
              nomPrenom.replaceAll("\\s+$", ""),                                    
              ", immatriculé à la caisse Nationale de Sécurité Sociale sous le numéro  ",                                     
               cnss.replaceAll("\\s+$", ""),                                
              ", travaille dans notre société depuis le ",
              dateEntree+ "." + newline+newline,                                
              civilite,         //regular
              nomPrenom.replaceAll("\\s+$", ""),                                          
              " est employé actuellement en qualité de " +
              Qualif.replaceAll("\\s+$", "") + " "+
                SituatProf.replaceAll("\\s+$", ""),
                " catégorie "+Categ.replaceAll("\\s+$", ""),
                " échelon "+ech.replaceAll("\\s+$", ""),
                ", conformément à la Convention Collective Nationale de l’Industrie Laitière et Dérivés.",
                newline +newline,
                "Cette attestation est délivrée à l’intéressé, sur sa demande, pour servir et valoir ce que de droit."


             };

    String[] initStyles =
            { "centeredBold", "regular", "regular", "regular", "regular",
              "regular", "regular", "regular", "regular",
              "regular", "regular", "regular", "regular", "regular", "regular"
            };

    JTextPane textPane = new JTextPane();
    textPane.setContentType("text/html");
    textPane.setText("<html><center><b>  </b></center></html>");
    StyledDocument doc = textPane.getStyledDocument();

    addStylesToDocument(doc);

    try {
        for (int i=0; i < initString.length; i++) {
            doc.insertString(doc.getLength(), initString[i],
                             doc.getStyle(initStyles[i]));
        }
    } catch (BadLocationException ble) {
        System.err.println("Couldn't insert initial text into text pane.");
    }

    return textPane;
}

protected void addStylesToDocument(StyledDocument doc) {
    //Initialize some styles.
    Style def = StyleContext.getDefaultStyleContext().
                    getStyle(StyleContext.DEFAULT_STYLE);

    Style regular = doc.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "Calibri");
    StyleConstants.setFontSize(regular, 16);

    Style s = doc.addStyle("italic", regular);
    StyleConstants.setItalic(s, true);

    s = doc.addStyle("bold", regular);
    StyleConstants.setBold(s, true);

    doc.addStyle("centeredBold", regular);
    SimpleAttributeSet center=new SimpleAttributeSet();
    StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
    StyleConstants.setBold(center, true);
    StyleConstants.setFontSize(center, 26);
    StyleConstants.setFontFamily(center, "Cambria");
    doc.getStyle("centeredBold").addAttributes(center);

    s = doc.addStyle("small", regular);
    StyleConstants.setFontSize(s, 10);

    s = doc.addStyle("large", regular);
    StyleConstants.setFontSize(s, 16);

    s = doc.addStyle("icon", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);



    s = doc.addStyle("button", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);



}


}

Any help would be appreciated and thank you in advance.

Upvotes: 2

Views: 6571

Answers (3)

camickr
camickr

Reputation: 324118

but they are all solutions about aligning all the text, and there are non about aligning one word or a part of the text.

You can only change the alignment for an entire line. There is no reason you can't have one line centered another right justifed and another left justified. You just need to change the paragraph attributes for the text that is going to be inserted (or has already been inserted.

The example you saw showed how to change the alignment for all the text currently in the Document, but this does not mean you can't change the alignment line by line.

For example:

JTextPane textPane = new JTextPane();
textPane.setText( "this line is centered" );
StyledDocument doc = textPane.getStyledDocument();

//  Define paragraph (line) attributes

SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);

SimpleAttributeSet left = new SimpleAttributeSet();
StyleConstants.setAlignment(left, StyleConstants.ALIGN_LEFT);

// change all lines in the Document to be centered

doc.setParagraphAttributes(0, doc.getLength(), center, false);

// all newly added line will be left justified

doc.setParagraphAttributes(doc.getLength(),1 , left, false);

//  Add some text

try
{
    doc.insertString(doc.getLength(), "\newly added text is left justified", null );
}
catch(Exception e) {}

and as i understood, the Jtextpane supports formatting better then the editorpane,

JEditorPane supports the power of HTML which is powerful, but you need to covert the text to HTML and create all the HTML tags. I find using a JTextPane will simple text and using attributes is easier to code and modify.

Upvotes: 4

StanislavL
StanislavL

Reputation: 57381

You can try to center it manually.

Calculate the word's width and calculate the JTextPane's widht. Then get additional shift and set paragraph's left indent to the shift.

Another potentially better solution would be to use TabStop with ALIGN_CENTER. So you can define the TabStop with position equals the center x and set the alignment to be CENTER. Then insert \t char just before the word.

UPDATE: TabStop clarification.

You can define TabSet paragraph attribute. See StyleConstants

public static void setTabSet(MutableAttributeSet a, TabSet tabs)

TabSet has the constructor

public TabSet(TabStop[] tabs)

Then see TabStop constructor

public TabStop(float pos, int align, int leader)

where you can set center align

Then just call

doc.setParagraphAttributes(theAttrsWithTabSet);

Upvotes: 1

Roan
Roan

Reputation: 1206

You could use html for aligiment and colors and bold:

First you need to set the datatype to html like:

textarea.setContentType("tekst/html");

After that you can use html formatting to customize the look:

For example a big font and centered and bold you would do like this:

textarea.setText("<html><center><b><font size=30 color=rgb(1,1,1)>  Text   </font></b></center></html>");

This is what the different parts do:

  1. <html> and </html> : These allow you to use all other html tags
  2. <center> and </center> : These center the tekst
  3. <b> and </b> or <strong> and </strong> : These make the text bold
  4. <font size=xx color=rbg(r,g,b)> and </font> : These do the size and color for the color you can also use preset colors like: color=black

Also more HTML tag can be found here: http://www.w3schools.com/html/default.asp

I hope this helps and good luck with your code :).

EDIT:

For multiple format apply multiple tag a tag is only active till it's colsed . So I you do this:

<html><font color=red>HI</font><font color=green>HI</font></html>.

Now the first HI is red and the second one is green. So you can mix around tags as you like. So only everything between <center> and </center> is centered.

Smiliar here:

<html><b>HI</b>HI</html>

Only the first HI is bold the second one is normal.

I hope this expains it a bit more.

Upvotes: 3

Related Questions