Centering Text in JTextArea

How can I center texts in JTextArea?
"jta.setAlignemtX(CENTER)" +
"jta.setAlignemtY(CENTER)" dont work.
I need a little assistense.
Dirk

I apologize for the above wrong answer!
Why dont u use a JTextPane instead of JTextArea
JTextPane text=new JTextPane();
SimpleAttributeSet set=new SimpleAttributeSet();
StyledDocument doc=text.getStyledDocument();
StyleConstants.setAlignment(set,StyleConstants.ALIGN_CENTER);
text.setParagraphAttributes(set,true);

Similar Messages

  • Centered text in JTextArea (java)

    how to center multiple line of text both vertically and horizontally in JTextArea ?

    Try:
    <html><center>text to center</center></html>
    V.V.viravan's way is the way to do it. Yoiu can use HTML for all sorts of things:
    <html><h1>text</h1></html> gives bigger text.
    <html><font color="cc3333">Set hexdecimal font color</font></html>
    You see the idea. :)

  • Center TEXT in JTextArea?

    Is it possible to center text in a JTextArea?
    I searched it but nothing on the web ... Is there another way to do this?
    with JTextPane or JTextEditor?
    I want just to center some text ....
    Thanks

    Do you want editable centered text or do you just want to display centered text and thought that JTextArea/JEditorPane/JTextPane was the only way to do it?
    If you just need to display centered text, you can use JLabel with HTML tags:
    Example:
    String message = "<HTML><CENTER>Centered Text!!!<BR>With line breaks even!!!</CENTER><HTML>"
    JLabel centered = new JLabel(message);

  • How to print diffrent color and diffrent size of text in JTextArea ?

    Hello All,
    i want to make JFrame which have JTextArea and i append text in
    JTextArea in diffrent size and diffrent color and also with diffrent
    fonts.
    any body give me any example or help me ?
    i m thanksfull.
    Arif.

    You can't have multiple text attributes in a JTextArea.
    JTextArea manages a "text/plain" content type document that can't hold information about attributes ( color, font, size, etc.) for different portions of text.
    You need a component that can manage styled documents. The most basic component that can do this is JEditorPane. It can manage the following content types :
    "text/rtf" ==> via StyledDocument
    "text/html" ==> via HTMLDocument
    I've written for you an example of how a "Hello World" string could be colorized in a JEditorPane with "Hello" in red and "World" in blue.
    import javax.swing.JEditorPane;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledEditorKit;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.SimpleAttributeSet;
    import java.awt.Color;
    public class ColorizeTextTest{
         public static void main(String args[]){
              //build gui
              JFrame frame = new JFrame();
              JEditorPane editorPane = new JEditorPane();
              frame.getContentPane().add(editorPane);
              frame.pack();
              frame.setVisible(true);
              //create StyledEditorKit
              StyledEditorKit editorKit = new StyledEditorKit();
              //set this editorKit as the editor manager [JTextComponent] <-> [EditorKit] <-> [Document]
              editorPane.setEditorKit(editorKit);
              StyledDocument doc = (StyledDocument) editorPane.getDocument();
              //insert string "Hello World"
              //this text is going to be added to the StyledDocument with positions 0 to 10
              editorPane.setText("Hello World");
              //create and attribute set
              MutableAttributeSet atr = new SimpleAttributeSet();
              //set foreground color attribute to RED
              StyleConstants.setForeground(atr,Color.RED);
              //apply attribute to the word "Hello"
              int offset = 0; //we want to start applying this attribute at position 0
              int length = 5; //"Hello" string has a length of 5
              boolean replace = false; //should we override any other attribute not specified in "atr" : anwser "NO"
              doc.setCharacterAttributes(offset,length,atr,replace);
              //set foreground color attribute to BLUE
              StyleConstants.setForeground(atr,Color.BLUE);
              //apply attribute to the word "World"
              offset = 5; //we include the whitespace
              length = 6;
              doc.setCharacterAttributes(offset,length,atr,replace);
    }

  • Clickable text in JTextArea?

    Hi all,
    I'm writing a program that populates a textarea with medical terms and such. And, the problem is I need to give an explanation to the more difficult words by allowing the user to click on the words and a popup window with the explanations will appear. I'm not familiar with the mouse clicks technology in Java, so please help if you can!
    Also, any suggestions on how the data can be stored/retrieved when I'm using a MySQL database?
    Many thanks!

    For this you have to add mouse listener in a text area. So that on mouse click you can do something.
    try following code, Run it and double click on some word.
    import java.awt.BorderLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.*;
    public class TextAreaDemo extends JPanel{
    private JTextArea text = null, answer = null;
    public TextAreaDemo(){
    text=new JTextArea("Hi all,\nI'm writing a program that populates a textarea with medical terms and " +
    "such. And, the problem is I need to give an explanation to the more difficult words " +
    "by allowing the user to click on the words and a popup window with the explanations " +
    "will appear. I'm not familiar with the mouse clicks technology in Java, so please " +
    "help if you can!\n\nAlso, any suggestions on how the data can be stored/retrieved " +
    "when I'm using a MySQL database?\n\nMany thanks!");
    answer=new JTextArea(3, 20);
    answer.setEditable(false);
    setLayout(new BorderLayout());
    add(new JScrollPane(text));
    add(new JScrollPane(answer), BorderLayout.SOUTH);
    text.addMouseListener(new MyMouseListener());
    class MyMouseListener extends MouseAdapter{
    public void mouseClicked(MouseEvent e){
    if(e.getClickCount() == 2){
    answer.setText("Do you want to know about:\n\t" + text.getSelectedText());
    public static void main(String argv[]){
    JFrame frame=new JFrame();
    frame.setContentPane(new TextAreaDemo());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
    May help you.
    Regards,

  • Centered text in PDF

    Hi
    I am new to this Acrobat SDK forum. I am trying to write a PDF code, but I have problems centering text. Below is a short "program" that writes the text "Centered text" starting at position x=100, y=600. But how do I center this text at some position, say x=200, y=600 ?  Can anyone help?
    - gullipeX
    %PDF-1.4
    1 0 obj
       << /Type /Catalog
          /Outlines 2 0 R
          /Pages 3 0 R
       >>
    endobj
    2 0 obj
       << /Type /Outlines
          /Count 0
       >>
    endobj
    3 0 obj
       << /Type /Pages
          /Kids [ 4 0 R ]
          /Count 1
       >>
    endobj
    4 0 obj
       << /Type /Page
          /Parent 3 0 R
          /MediaBox [ 0 0 612 792 ]
          /Contents 5 0 R
          /Resources << /ProcSet 6 0 R
                      /Font << /F1 7 0 R >>
                      >>
       >>
    endobj
    5 0 obj
       << /Length 73 >>
    stream
    BT
       /F1 24 Tf
       100 600 Td
       ( Centered text ) Tj
    ET
    endstream
    endobj
    6 0 obj
       [ /PDF /Text ]
    endobj
    7 0 obj
       << /Type /Font
          /Subtype /Type1
          /Name /F1
          /BaseFont /Helvetica
          /Encoding /MacRomanEncoding
       >>
    endobj
    xref
    0 8
    0000000000 65535 f
    0000000009 00000 n
    0000000074 00000 n
    0000000120 00000 n
    0000000179 00000 n
    0000000364 00000 n
    0000000466 00000 n
    0000000496 00000 n
    trailer
       << /Size 8
          /Root 1 0 R
       >>
    startxref
    625
    %%EOF

    Hi, Irosenth and others again.
    To try to solve my problem (because I do not know how to do this in PDF), I made a short PostScript program to check the length of the characters in Helvetiva 10 pt. A part of the program is shown below. If I have the length, I can calculate the centered position of the text in my C or Fortran program, that makes the PDF file.  This investigation gave, for instance, the lengths for A, B and W as:
    A:  6.66797
    F:  6.10840
    W: 9.43945
    When I placed the EPS file into Adobe InDesign a bit different values came out:
    A:  6.66959
    F:  6.10963
    W: 9.43942
    ... and still different in Adobe Photoshop:
    A:  6.67081
    F:  6.11075
    W: 9.44115
    I have the feeling that character lengths are given as integers in the font file (not as real numbers) and I actually have to multiply these lengths (for 10 pt. Helvetica)  with some unknown value to find the "correct" lengths of the given characters. Does anyone know the actual length of the character A in Helvetica for instance?
    PostScript program:
    /Helvetica findfont
    dup length dict begin
      {1 index /FID ne {def} {pop pop} ifelse} forall
      /Encoding ISOLatin1Encoding def
      currentdict
    end
    /Helvetica-ANSI exch definefont pop
    gsave
    /str 20 string def
    /Helvetica-ANSI findfont 10 scalefont setfont
    (A ) 50  750 moveto show
    (A)  stringwidth pop str cvs  80 750 moveto show
    (F ) 50  700 moveto show
    (F)  stringwidth pop str cvs  80 700 moveto show
    (W ) 50  650 moveto show
    (W)  stringwidth pop str cvs  80 650 moveto show
    grestore

  • How to display giant text in JTextArea???

    hi!.......how can i display lets say 20mbs of text in JTextArea?......i try to display but it only show till 2-3mb then the rest is empty.....anyone knows how?

    Hi, I don't know how.
    But I know that it wouldn't be so nice loading 20/30 Mb of text at once. You could load a smaller amount of data like 1 Mb and show it. Then when the user scrolls to bottom you could load more text.
    pseudocode :
    - load some text and show it
    - while true
    if user scrolls down
    * actualize text showed loading more text if necesary
    if user scrolls up
    * actualize text showed
    - end while
    Hope it helps.

  • Smartforms centered text formatting

    Hi, i have a problem developing a smartform form, when i use centered text it should appear:
           Avenida das Forças Armadas, 111 2º C
                           1600-045 LISBOA
                    Nº Contribuinte xxxxxxxxx
    Tel. +351 21 xxx xx 00 - Fax +351 21 xxx xx xx
    In the MS WORD editting box it looks right, but when i print the form the output widens the spaces between words like this:
                         Avenida       das      Forças      Armadas,     111    2º    C
                                                     1600-045     LISBOA
                                             Nº    Contribuinte     xxxxxxxxx
    Tel.    +351     21     xxx     xx     00    -    Fax      +351      21     xxx      xx     xx
    Thank you for the help.
    Edited by: tiagoramalhais on Feb 24, 2011 8:10 PM

    The Print output depends on the paper Size ! Why don't you try using a Standard Text for your requirement ?

  • HTMLEditorKit Centering Text

    Hello,
    I am writing a basic html editor which uses a textPane and java's HTMLEditorKit. The program allows the html to be saved.
    At the moment the text can only be written in a row by row form. And I would like to add the option of centering text, and images Which could be switch on and off, suchas in Microsoft's word.
    Could anyone provide an example of how to achieve this, or over some guidance.
    Thank you

    Thanks,
    I had a look at the site, though I could not find the answer, to how to use the java tools StyleSheet HTMLDocument and HTMLEditorKit kit. And allow the user to center text and images within a textpane, which would add the center tag to the HTMLDocument which contains the html template.
    Could you possibly advice further?

  • Centering text & wrapping words on lines

    Hi all,
    I need to have a JLabel that centers the text in it, and allows for multiple lines, where if a line is too long, it wraps onto the next line.
    I started off with a JTextArea, setting "setLineWrap" and "setWrapStyleWord", and this works fine for long lines of text. But, I need to have the text centered as well. Is there any way of doing this? I know JTextPane can do it, but I can't see how to do it in JTextArea.
    any help much appreciated,
    Justin

    Use a JLabel, with HTML text content and set the preferred size of the label as well. This will do auto line wrap;
    ie. ew JLabel("<html><center>The long text</center></html>");ICE

  • Help centering text

    I'm trying to center a line of text in the text area.
    If the text entered can be displayed on one line, I would like the text centered; otherwise it should use the word wrap.
    I tried creating a method called center:
    // Defined outside this method, but shown since it is being referenced.
    int textAreaWidth = (int) textArea.getPreferredScrollableViewportSize().getWidth();     public String center(String text)
         int stringWidth = metrics.stringWidth(text);
         if (stringWidth > textAreaWidth)
              // Only handles text shorter than one line.
              return text;
         int availableWidth = textAreaWidth - stringWidth;
         int availableSpaces = availableWidth / metrics.charWidth(' ');
         int spacesToAdd = availableSpaces / 2;   
         // Adds the leading spaces to the text to center it.
         // Adds a trailing space as well to test the actual metrics length.
         for (int index = 0; index < spacesToAdd; index++)
              text = " " + text + " ";
         return text;
    }I coudln't find anything to use in the Java Doc, so I thought I'd write one to help me out.
    Testing it, I used:
    textArea.setText(center("m"));The issue is that the JTextArea is returning a width of 300. That is correctly set, and returning the right width.
    The string width is returning at 11, which is expected for the letter m.
    The available width is 289. Also correct. 300 - 11 = 289
    The metrics character width of a space is 3.
    The spacesToAdd returns at 48.
    A string with a metrics width of 299 is returned. That being, 48 spaces and the letter m.
    However, the JTextArea displayed in the JPanel shows this text wrapping onto a second line -- indicating the JTextArea displayed is not the actual width I set it to.
    The code to setup the JTextArea is as follows:
    JPanel panel = new JPanel();
    textArea = new JTextArea();
    textArea.setPreferredSize(new Dimension(300, 60));
    textArea.setLineWrap(true);
    textArea.setFocusable(false);
    textArea.setEditable(false);
    textArea.setWrapStyleWord(true);
    textArea.setFont(APP_FONT);
    scrollPane = new JScrollPane(textArea);
    scrollPane.setBorder(BorderFactory.createEmptyBorder());
    panel.add(scrollPane);What am I doing wrong?
    I suppose I could use a document and set styles... but ... I was trying to get this working...
    Help would be appreciated.. Thanks!

    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the posted code retains its original formatting.

  • Centerned text in JTextArea

    How can I have it so that all my text inside a JTextArea is centered? I want it to be centered as I am typing in it.

    Here's a search of the forums for topics with the words jtextarea and center in the title
    http://onesearch.sun.com/search/developers/index.jsp?and=jtextarea+center&nh=10&phr=&qt=&not=&field=title&since=&col=devforums&rf=0&Search.x=42&Search.y=10

  • Highlighting text in JtextArea

    I want to highlight text in a JTextArea each time the text changes and therefore i use a DocumentListener and also the following :
    public Highlighter.HighlightPainter redHighlightPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.red);
    Highlighter hilite = gJTextArea.getHighlighter();
    hilite.addHighlight(bufferBegin , bufferEnd, redHighlightPainter);
    but the text remains black
    How can you explain this?
    Thanks

    I have used the same exact piece of code in a JTextArea and it works perfectly. Maybe your problem is elsewhere in the code because this should work fine. Are you sure that the Document listener is fireing when changes occur?

  • How do I put two centered text in a PAGE_START in BorderLayout ?

    Hi everybody.
    I am using a BorderLayout and in PAGE_START section I want to put a title(centered, with two rows). I don't know how to do that. When I put my text there, is on the left side.
    Thanks.
    Edited by: blackblack13 on Jul 18, 2009 1:08 AM

    Aaa yes, you're right. The thing with two JLabels is very good, I didn't think about that. But with HTML I don't know how to use it. Where can I find smth about that?
    Thanks a lot !

  • Can't update text in JTextArea! Can you help?

    [Update: If I remove the transparency everything is fine. However, I really need the transparency..]
    Hi,
    I have the simplest question, but I can't seem to get an answer to it. The problem is very simple: I have defined a JTextArea and I'm reading text into it. The problem is that the old text does not disappear, and the new text is pasted on top, making it unreadable. As an "act of desperation" I fixed this by setting the area invisible, updating it and setting it visible again, as you can see in the code. It works, but now it blinks in the screen (quite annoying!).
    Is there a smarter way to to this? I need this on a transparent window (see class init below), overlayed on another JFrame.
    I am on Mac OS X.
    I hope some of you can help me with this problem
    Thanks a lot in advance
    Lele
    public void UpdateOverlay(){
            try{
                BufferedReader b = this.ReadUrl("http://localhost/~"+System.getProperty("user.name")+"/overlaytext.txt");
                this.Overlay.setVisible(false);
                this.OverlayText.read(b, null);
                this.Overlay.setVisible(true);
            }catch(Exception e){
                e.printStackTrace();
        }Here you can see how I have initialized the class
    public class MyClass {
        //Overlay section
        public JFrame Overlay=new JFrame("Overlay");
        public Color OverlayColor=new Color(0.0f,0.0f,0.0f,0.0f);
        public JTextArea OverlayText=new JTextArea();
        public long Refresh_time=200;//ms
        /** Creates a new instance of MyClass */
        public MyClass(AWT1UpFrame f) {
            int width=270,height=170,border_x=20,border_y=20;
            //Initialize Overlay
            this.Overlay.setVisible(false);
            this.Overlay.setBackground(this.OverlayColor);
            this.Overlay.setLocationRelativeTo(null);
            this.Overlay.setUndecorated(true);
            this.Overlay.setSize(width,height);
            System.out.println("loc="+f.getLocation());
            int x = f.getLocation().x+border_x;
            int y = f.getLocation().y +f.getSize().height - border_y - height;
            this.Overlay.setLocation(x, y);
            this.Overlay.add(this.OverlayText);
            this.Overlay.setAlwaysOnTop(true);
            this.OverlayText.setLineWrap(true);
            this.OverlayText.setWrapStyleWord(true);
            this.OverlayText.setForeground(Color.GREEN);
            this.OverlayText.setBackground(this.OverlayColor);
            this.OverlayText.setFont(new Font("Arial", Font.ROMAN_BASELINE, 16));
    /* and so on*/Edited by: Lele on Oct 25, 2007 4:22 PM

    Hi, so this is the class. If I keep it like this, it simply overwrites old text with the new (like JTextArea thinks that the old text is a part of the background to be buffered). If I set it invisible and back to visible it works, but it blinks.
    How can I let JTextArea understand that it shouldn't consider the old window as a background? Should I use another class?
    Pls keep in mind that I'm on Mac, so maybe it's a Mac-specific thing, but I'd like to know..
    Thanks
    Lele
    package transparency;
    import java.net.*;
    import javax.swing.*;
    import javax.xml.parsers.*;
    import java.awt.*;
    import java.awt.font.*;
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    import java.util.List;
    import apple.awt.CTextArea;
    public class Overlay {
        //Overlay section
        public JFrame Overlay=new JFrame("Overlay");
        public Color OverlayColor=new Color(0.0f,0.0f,0.0f,0.0f);
        public JTextArea OverlayText=new JTextArea();
        public long Refresh_time=200;//ms
        /** Creates a new instance of Overlay */
        public Overlay() {
            int width=270,height=170,border_x=20,border_y=20;
            //Initialize Overlay
            this.Overlay.setVisible(false);
            this.Overlay.setBackground(this.OverlayColor);
            this.Overlay.setLocationRelativeTo(null);
            this.Overlay.setUndecorated(true);
            this.Overlay.setSize(width,height);
            //System.out.println("loc="+f.getLocation());
            //int x = f.getLocation().x+border_x;
            //int y = f.getLocation().y +f.getSize().height - border_y - height;
            //this.Overlay.setLocation(x, y);
            this.Overlay.add(this.OverlayText);
            this.Overlay.setAlwaysOnTop(true);
            this.OverlayText.setLineWrap(true);
            this.OverlayText.setWrapStyleWord(true);
            this.OverlayText.setForeground(Color.GREEN);
            this.OverlayText.setBackground(this.OverlayColor);
            this.OverlayText.setFont(new Font("Arial", Font.ROMAN_BASELINE, 16));
            this.Overlay.setVisible(true);
        public void UpdateOverlay(){
            try{
                //Reading URL
                //String Address="http://localhost/~"+System.getProperty("user.name")+"/overlaytext.txt";
                //URL url= new URL(Address);
                //BufferedReader b = new BufferedReader(new InputStreamReader(url.openStream()));
                //this.Overlay.setVisible(false);
                //this.OverlayText.read(b, null);
                //this.Overlay.setVisible(true);
                //Test
                //this.Overlay.setVisible(false);
                String RandomText="The time is: "+System.currentTimeMillis();
                this.OverlayText.setText(RandomText);
                //this.Overlay.setVisible(true);
            }catch(Exception e){
                e.printStackTrace();
    }.. and this is the main
    package transparency;
    import java.net.*;
    import javax.swing.*;
    import javax.xml.parsers.*;
    import java.awt.*;
    import java.awt.font.*;
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    import java.util.List;
    import transparency.*;
    public class Main {
        /** Creates a new instance of Main */
        public Main() {
        public static void main(String[] args) {
            JFrame f=new JFrame();
            f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
            f.setVisible(true);
            Overlay ov=new Overlay();
            try{
                while(f.isVisible()){
                    ov.UpdateOverlay();
                    Thread.sleep(100);
            }catch(Exception e){
                e.printStackTrace();
    }Edited by: Lele on Oct 26, 2007 3:40 AM

Maybe you are looking for