【问题标题】:Center alignment of a word in JTextPaneJTextPane中单词的中心对齐
【发布时间】:2014-08-15 22:17:57
【问题描述】:

我有一个需要格式化的文本,文本的第一个单词需要用大字体加粗并居中。

为了进行这种格式化,我在 JTextComponents 的 oracle 教程中使用来自 TextSamplerDemo.java 的解决方案,该解决方案效果很好,但居中不起作用!

现在我知道Stack Overflow 中已经有关于在 JTextPane 和 other forums 上对齐文本的答案,但它们都是关于对齐所有文本的解决方案,并且没有关于对齐一个单词或部分文本。

再一次,字体、大小和“粗体”(不知道正确的术语,但你明白我的意思;-p)它们都起作用,但居中不起作用。

这是我用来设置 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);



}


}

任何帮助将不胜感激,并在此先感谢您。

【问题讨论】:

  • 你有没有试过把所有的文字都换成然后用html居中对齐?
  • 没有。实际上...我是 HTML 中的“零”,所以我不知道该怎么做。如果您能提供帮助,我将不胜感激。顺便说一句,如果这是相关信息,文本将被打印出来。
  • doc的数据类型是什么?
  • 如果你打算使用 html 进行居中,你可以这样做:&lt;html&gt;&lt;center&gt; Text &lt;/center&gt;&lt;/html&gt;,如果你想要 tekst 粗体,你可以这样做:&lt;html&gt;&lt;center&gt;&lt;b&gt; Tekst &lt;/b&gt;&lt;/center&gt;&lt;/html&gt;,颜色可以通过&lt;font&gt; 标签来完成,例如: &lt;font color=rgb(1, 1, 1)&gt;我希望这会有所帮助:)。
  • 顺便说一下,如果您需要有关 HTML 标签的更多信息,可以在这里找到它们:w3schools.com/html/default.asp

标签: java styles alignment jtextpane


【解决方案1】:

但它们都是对齐所有文本的解决方案,而不是对齐一个单词或文本的一部分。

您只能更改整行的对齐方式。没有理由不能让一条线居中,另一条右对齐,另一条左对齐。您只需要更改将要插入(或已经插入)的文本的段落属性。

您看到的示例显示了如何更改 Document 中当前所有文本的对齐方式,但这并不意味着您不能逐行更改对齐方式。

例如:

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) {}

据我了解,Jtextpane 比编辑器窗格更支持格式化,

JEditorPane 支持 HTML 的强大功能,但您需要将文本转换为 HTML 并创建所有 HTML 标签。我发现使用 JTextPane 将是简单的文本,并且使用属性更容易编码和修改。

【讨论】:

  • 感谢您的回答,它非常清晰和简单,但我实际上尝试了另一种使用 html 的解决方案:我使用了 setText() 并将所有文本以及 html 格式化功能放入其中。没有 styledDocuments 什么都没有。 (我猜是最简单但最愚蠢的方法:p)
【解决方案2】:

您可以将 html 用于对齐、颜色和粗体:

首先您需要将数据类型设置为 html,例如:

textarea.setContentType("tekst/html");

之后,您可以使用 html 格式来自定义外观:

例如,一个大字体和居中粗体你会这样做:

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

这是不同部分的作用:

  1. &lt;html&gt;&lt;/html&gt; :这些允许您使用所有其他 html 标签
  2. &lt;center&gt;&lt;/center&gt; :它们以 tekst 为中心
  3. &lt;b&gt;&lt;/b&gt;&lt;strong&gt;&lt;/strong&gt; :这些使文本变为粗体
  4. &lt;font size=xx color=rbg(r,g,b)&gt;&lt;/font&gt; :这些为颜色设置大小和颜色,您也可以使用预设颜色,例如:color=black

还可以在此处找到更多 HTML 标记: http://www.w3schools.com/html/default.asp

我希望这对您的代码有所帮助并祝您好运:)。

编辑:

对于多种格式应用多个标签,标签仅在它被 colsed 之前处于活动状态。 所以我你这样做:

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

现在第一个 HI 是红色的,第二个是绿色的。所以你可以随意混合标签。所以只有&lt;center&gt;&lt;/center&gt; 之间的所有内容都是居中的。

这里是类似的:

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

只有第一个 HI 是粗体,第二个是正常的。

我希望这能解释得更多。

【讨论】:

  • 它确实有效,但又适用于整个文本:/!使用 setText() 方法将格式应用于所有文本,正如我的问题所提到的,我需要对一个单词进行格式化,并且正如我之前所说,我正在使用 oracle doc tutorial 中的解决方案,其中初始化文本窗格的内容是通过 StyledDocument 完成的。我将编辑我的问题并添加所有代码以澄清问题。
  • 不,我说得很清楚,但也许我还不够清楚。我将编辑我的答案。
  • 查看 html 标签仅适用于它们之间的内容。我希望这会有所帮助:)。
  • 是的,这是正确的,但您需要一次设置所有文本。因为如果您执行setText("&lt;html&gt; &lt;/html"); 并添加一些文本,我将在最后添加一些文本,它看起来像:"&lt;html&gt; &lt;html&gt;&lt;b&gt;HI&lt;/b&gt; 然后它不起作用,因为标签需要介于 和 跨度>
  • @user3610008 顺便说一句,我会给你 5 声望;p
【解决方案3】:

您可以尝试手动居中。

计算单词的宽度并计算 JTextPane 的宽度。然后获得额外的移位并将段落的左缩进设置为移位。

另一个可能更好的解决方案是将 TabStop 与 ALIGN_CENTER 一起使用。因此,您可以定义位置等于中心 x 的 TabStop,并将对齐方式设置为 CENTER。然后在单词之前插入 \t char。

更新: TabStop 说明。

您可以定义TabSet 段落属性。见StyleConstants

public static void setTabSet(MutableAttributeSet a, TabSet tabs)

TabSet 有构造函数

public TabSet(TabStop[] tabs)

然后看 TabStop 构造函数

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

你可以在哪里设置中心对齐

然后打电话

doc.setParagraphAttributes(theAttrsWithTabSet);

【讨论】:

  • 我很抱歉,但由于我是 Java 新手,如果您以更好的方式提出您的问题,尤其是 TabStop 部分,我将不胜感激,我没有明白,它是 Java 中的类还是究竟是什么(原谅我的无知:p)
  • 谢谢你的帮助,下次我需要格式化文本时,我会记住这一点,同时,Roan给出的解决方案有效,所以我会使用它!再次感谢您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-01
  • 2013-11-27
  • 2023-03-04
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
相关资源
最近更新 更多