2

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.

Community
  • 1
  • 1
user3610008
  • 79
  • 2
  • 11
  • 1
    Did you try to wrap all the text into and then use html center alignment? – Thomas Jun 25 '14 at 11:19
  • No. Actually... I'm a "Zero" in HTML so i wouldn't know how to do that. If you could help with that i'd appreciate it. By the way, the text is going to be printed in case that's a related information. – user3610008 Jun 25 '14 at 11:24
  • What the datatype of doc? – dARKpRINCE Jun 25 '14 at 11:28
  • 2
    If you are going to use html for centering you could do: `
    Text
    ` and if you want tekst bold you could do: `
    Tekst
    ` and colors can be done by the `` tag like: `` I hope this helps :).
    – Roan Jun 25 '14 at 11:33
  • 1
    By the way if you need more information on HTML tags you can find them here: http://www.w3schools.com/html/default.asp – Roan Jun 25 '14 at 11:34
  • @dARKpRINCE I didn't set the datatype yet, it's the default type (I don't what that is, i guess it's HTML) Edit: I verified and the datatype is plain text. – user3610008 Jun 25 '14 at 11:57
  • @Roan thank you for your help, i'll try your solution and give you feedback. Logically i should set the datatype to HTML to use your solution, is that correct? If you could just put your comment as an answer so i can mark the question as solved if your solution works. – user3610008 Jun 25 '14 at 11:58
  • I posted an aswer I hope this works and you indeed need to set the data type (i think atleast not sure) – Roan Jun 25 '14 at 12:13

3 Answers3

4

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Thank you for your answer, it's really clear and simple, but i actually tried another solution using html: i used the setText() and put all of the text in it plus the html formatting features. no styledDocuments no nothing. (i guess the simplest but stupidest way :p ) – user3610008 Jun 25 '14 at 15:12
3

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.

Roan
  • 1,200
  • 2
  • 19
  • 32
  • It actually worked but again for the whole text :/! Using the setText() method applies the formatting to all of the text, and as my question mentions, i need one word to be formatted, and also as i said before i'm using the the solution from the oracle doc tutorial where the initializing of the textpane is done through the StyledDocument. I'll edit my question and add all the code to clarify the problem. – user3610008 Jun 25 '14 at 12:27
  • No I was clear enough but maybe I just wasn't clear enough. I'll edit my answer. – Roan Jun 25 '14 at 12:36
  • See html tag only apply to what's between them. I hope this helps :). – Roan Jun 25 '14 at 12:43
  • So what you're saying is that i should use the setText() method to add "" and in the then when using the with StyledDocument in the correct position, i should add the "
    Tekst
    " String? If that's what you're saying, it didn't work for me (at least not for the "
    Tekst
    " part) Hope i am making myself clear and forgive the load of questions! Thank you.
    – user3610008 Jun 25 '14 at 12:48
  • 1
    yeah that's right but you need to set all the text at once. Because if you do `setText(" HI` and then it doesn't work because tag need to be between and – Roan Jun 25 '14 at 12:51
  • And if you have a lot of trouble with the JTextPane maybe look into JEditorPane it is a bit more html friendly I think. – Roan Jun 25 '14 at 12:52
  • I actually tried using the setText() method for the word in question, and it worked all fine, what i did exactly is (as you said in your last comment) textPane.setText("
    Tekst
    ") and then i used my doc to add other strings! About the editorPane, i looked up the difference between the JeditorPane, the JtextPane, and as i understood, the Jtextpane supports formatting better then the editorpane, that's why i used it, no need to change now since your solution worked. Anyway, thank you a lot for your help, and again sorry for the ignorance :D!
    – user3610008 Jun 25 '14 at 13:01
  • No problem glad to hear it worked and good luck with the rest of your code and don't forget to close the question. And if you are further intrested in html and Java see this: http://docs.oracle.com/javase/tutorial/uiswing/components/html.html – Roan Jun 25 '14 at 13:03
  • I would've voted for you, but i need 5 more reputation points to be able to vote! a "thank you" would do it i guess :p! – user3610008 Jun 25 '14 at 13:03
  • 1
    @user3610008 And by the way I'll give you that 5 reputation ;p – Roan Jun 25 '14 at 13:05
  • No problem :D have fun with it :D – Roan Jun 25 '14 at 14:21
1

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);
StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • I am sorry but since i am novice in Java i would appreciate if you formulate your question in a better way, especially the TabStop part, i didn't get that, is it a Class in Java or what exactly (forgive my ignorance :p ) – user3610008 Jun 25 '14 at 12:00
  • Thank you for you help i'll keep this in mind next time i need to format a text, meanwhile, the solution given by Roan worked, so i'll use it! Again, thank you. – user3610008 Jun 25 '14 at 14:23