Center text in a JTextArea

How can i get center the JTextArea text?

Here's some code I found on the forum for a JTextPane:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class TextPaneCenter
    JTextPane edit = new JTextPane();
    public TextPaneCenter()
         JFrame frame=new JFrame();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.getContentPane().add(new JScrollPane(edit));
        try
             edit.setEditorKit(new MyEditorKit());
             SimpleAttributeSet attrs=new SimpleAttributeSet();
             StyleConstants.setAlignment(attrs,StyleConstants.ALIGN_CENTER);
             StyledDocument doc=(StyledDocument)edit.getDocument();
             doc.insertString(0,"111\n2222222\n33333333333333",attrs);
             doc.setParagraphAttributes(0,doc.getLength()-1,attrs,false);
         catch (Exception ex)
             ex.printStackTrace();
         frame.setSize(300,300);
         frame.setLocationRelativeTo(null);
         frame.show();
    public static void main(String[] args) throws Exception
         new TextPaneCenter();
    class MyEditorKit extends StyledEditorKit
         public ViewFactory getViewFactory()
              return new StyledViewFactory();
        static class StyledViewFactory 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);
                       else if (kind.equals(AbstractDocument.SectionElementName))
                            return new CenteredBoxView(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);
        } // class StyledViewFactory
      } // class MyEditorKit
    class CenteredBoxView extends BoxView
         public CenteredBoxView(Element elem, int axis)
              super(elem,axis);
         protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans)
              super.layoutMajorAxis(targetSpan,axis,offsets,spans);
              int textBlockHeight = 0;
              int offset = 0;
              for (int i = 0; i < spans.length; i++)
                   textBlockHeight += spans[ i ];
              offset = (targetSpan - textBlockHeight) / 2;
//              offset = (targetSpan - textBlockHeight);
              for (int i = 0; i < offsets.length; i++)
                   offsets[ i ] += offset;
     }

Similar Messages

  • How do I center text in a JTextArea?

    Easy question! how can I center text being fed into a JTextArea?
    Thank you!!!!!!!!!!!

    Thanks for the reply. You seem to know swing pretty well. Is there a way to change the color of my actual font in a JText Area?
    Thanks again!!!!!!

  • How can I center text in a JTextArea?

    I'm coding my own little font selection frame, and want to display the sample text in a JTextArea, and want to know how I can get the text centered in the field. Does anyone know how this can be done? Thanks.

    Thanks Camrick, I'm disappointed that it will take so much to accomplish this. But I'm very appreciative of your response, and I will definitely put that code to use. Just not in time to turn in my assignment, lol. But thats ok, this function was beyond the requirements anyway, I just wanted to put in some bells and whistles.
    Cheers!

  • 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);

  • Center text in a text component with line wrapping

    I need to display dynamic text in a text component. I need line wrapping (on work boundaries) and also need horizontal and vertical center alignment.
    How do I do this? I saw a previous post on aligning text in a JTextArea that said to use a JTextPane but I don't see in JTextPane how to do word wrapping.
    Thanks,
    John

    //  File:          SystemInfoWindow.java.java
    //  Classes:     SystemInfoWindow
    //  Package:     utilities.msglib
    //  Purpose:     Implement the SystemInfoWindow class.
    //     Author:          JJB 
    //     Revision History:
    //     Date            By   Rel#  Description of change
    //     =============  ===  ====  ===============================================
    //     Jul 3, 2006   JJB  1.00  Original version
    //  Public Types / Classes          Type Description
    //  ========================     =============================================
    //     SystemInfoWindow
    package utilities.msglib;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JTextPane;
    import javax.swing.SwingUtilities;
    * TODO Enter description
    class SystemInfoWindow extends JDialog {
          * @param args
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        Test thisClass = new Test();
                        thisClass.setVisible(true);
                        SystemInfoWindow window = new SystemInfoWindow(thisClass);
                        window.setMessage("System shutdown in progress ... lot sof atatarte athis tis a sa logoint of tesxt it keeps going and going and going thsoreoiat afsjkjslakjs fshafhdskrjlkjsdfj");
                        window.setVisible(true);
         //     ------------------------  Inner Classes ---------------------
         static class Test extends JFrame {
              private JPanel jContentPane = null;
               * This is the default constructor
              public Test() {
                   super();
                   initialize();
               * This method initializes this
               * @return void
              private void initialize() {
                   this.setSize(300, 200);
                   this.setContentPane(getJContentPane());
                   this.setTitle("JFrame");
               * This method initializes jContentPane
               * @return javax.swing.JPanel
              private JPanel getJContentPane() {
                   if (jContentPane == null) {
                        jContentPane = new JPanel();
                        jContentPane.setLayout(new BorderLayout());
                   return jContentPane;
         //     ------------------------  Static Fields ---------------------
         private static final long serialVersionUID = -8602533190114692294L;
         //     ------------------------  Static Methods --------------------
         //     ------------------------  Public Fields ---------------------
         //     ------------------------  Non-Public Fields -----------------
         private JPanel jContentPane = null;
         private JTextPane textField = null;
         public SystemInfoWindow(JFrame frame) {
              super(frame);
              initialize();
              //setUndecorated(true);
              setLocationRelativeTo(frame);
              pack();
         //     ------------------------  Interface Implementations ---------
         //     ------------------------  Public Methods --------------------
         public void setMessage(String text){
              textField.setText(text);
              adjustSize();
         //     ------------------------  Non-Public Methods ----------------
         private void adjustSize(){
              Dimension oldSize = textField.getPreferredSize();
              textField.setPreferredSize(new Dimension(
                        oldSize.width, oldSize.height + 30));
              pack();
         //     ------------------------  Generated Code --------------------
          * This method initializes this
          * @return void
         private void initialize() {
              this.setSize(300, 200);
              this.setModal(true);
              this.setContentPane(getJContentPane());
              this.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowOpened(java.awt.event.WindowEvent e) {
                        //setLocationRelativeTo(MsgLibGlobals.parent);
                        pack();
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(new BorderLayout());
                   jContentPane.setMaximumSize(new java.awt.Dimension(50,2147483647));
                   jContentPane.add(getTextField(), java.awt.BorderLayout.CENTER);
              return jContentPane;
          * This method initializes textField     
          * @return javax.swing.JTextPane     
         private JTextPane getTextField() {
              if (textField == null) {
                   textField = new JTextPane();
                   textField.setEditable(false);
                   textField.setMaximumSize(new java.awt.Dimension(20,2147483647));
              return textField;
    }Message was edited by:
    BaltimoreJohn

  • How do I change the colour of text in a JTextArea?

    I was wondering if there is a method I could use to change certain parts of the text in a JTextArea to a different color, eg if you wished to highlight HTML tags in the source code, so they stand out from the rest of the text.
    cheerz

    Try this...
      // create text area
      JTextArea textArea = new JTextArea();
      // change text color to blue
      textArea.setForeground(Color.blue);
      // change background color to black
      textArea.setBackground(Color.black);

  • Getting the text from a JTextArea...

    hi, I'm making a perfect calculator program and I'm trying to add a Note Pad function to it, I also want to hide that so the other interface can be used; I can get it hided and come again but I'm wondering how could I get the text from the JTextArea INCLUSIVE the enters that are made withing it, so:
    theString = jTextArea1.getText();only gives me the text and no enters; suggestions?

    I think I displayed it wrongTwo things to keep in mind...
    Certain Swing components will just ignore newlines, so you have to be careful where/how you're displaying your multiline text strings. Some components will display it all as one line, some will only display the top line, some will even show \n instead of doing the newline. It all just depends.
    And JTextArea does support word wrapping, so just because it looks like there's a newline, there may not be one.

  • Vertically Center Text in a Text Box

    Just switched form Acrobt 6 to Acrobat Pro 9 and can't figure out how to verically center text in a text box.  When I select the text it gives me the properties bar shown below:
    Seems like a really dumb question because I know I could in Acrobat 6 and I don't know why they would take away that feature, but I can't find it anwywhere.

    The only time the More button is enabled is when I have the Text Box selected, and then the options pertain to the line weight, etc. of the box and not the text.  When I select the text the More button is not enabled and the only options properties are the ones shown above.
    I made the Text Box by going to "Tools", "Comment & Markup", "Text Box Tool".  I have not seen anything that says Multiline and when I searched help it only talked about multiline fields in forms.
    Thanks for the quick responses.

  • How to center text in shapes

    how to center text in shapes. specifically circles.  I want text to be centered directly in the middle

    A lot depends on what you mean by centered, the number of lines of text, the actual font, and whether there are descenders.
    Using vertical justification set to centered may or may not work for you, depending on the above factors, as it depends on the baseline, I believe, rather than the acutal glyph dimensions. You could try adding baseline shift, I suppose, to make fine vertical adjustments, or you can bite the bullet and use the old-fashioned method of two frames.

  • CR duplication when Copy/Pasting text from a JTextArea

    I have a typical scenario of having text in a JTextArea. When I select some of that text and try to paste it either to an external text editor or even in the same JTextArea, I am getting extra line spaces in the screen.
    For example, if I have the following text:
    <a id=1>
       <b/>
    </a>When I copy paste it, I get:
    <a id=1>
       <b/>
    </a>When I looked to see what characters were being used for the CR, I see "\r\n". This is the standard line.seperator for Windows OS which is fine. When I save this text to a file using the Java I/O libraries, it is fine (no extra lines). But when copy/pasting it prints extra lines.
    Has anyone had similar problems?

    Has anyone had similar problems? No. How are you doing the copy/paste? Did you write your own routines or are you using the default Actions. By default, when a Document is loaded it will convert the "\r\n" end of line string to "\n" and store the single character in the Document. When you use the getText(..) method the enod of line string will be expanded to "\r\n" on a Windows system, but this should not happen in a copy/paste operation. How do you add data to your text area?
    This section from the Swing tutorial on "Text Component Features" has a working example of using copy/paste:
    http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html

  • How can i turn a part of a text of  a JTextArea into bold??

    how can i turn a part of a text of a JTextArea into bold?? I mean i just want the selected text to do so and not all of the content of the JTextArea.
    Is there a way to do so??
    If not, is there another component that i can use to do so??
    [Rik]

    Use a JTextPane. Here's an example to get you started:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=342068

  • How can I assign a text file to JTextArea component??

    Hi every body, does any boody has a code for read a text file and show this text in a JTextArea??? I'm trying with a FileReader but the text doesn't appear well.
    Thanks in advance.
    Juan

    String s = "";
    BufferedReader reader =
                             new BufferedReader(new FileReader(path));
                        String temp = reader.readLine();
                        s += temp + "\n";
                        while (temp != null)
                             temp = reader.readLine();
                             if (temp != null)
                                  s += temp + "\n";
                        reader.close();
    textArea.setText(s);

  • Center Text in TextField Dynamically

    How on earth do you center text within a text field
    dynamically....e.g. textField.align = "center" or
    textField.autoSize = "center" ....nothing works?
    BTW...is it just me or is the adobe site just plain slow and
    almost unusable to everyone else too. It has to be one of the
    slowest loading sites I visit and the menu at top takes forever to
    load completely also, Has there been discussion on that?

    You are using the align property incorrectly. You do not
    apply it directly to the textfield but to the textformat property.
    var format:TextFormat = new TextFormat();
    format.align = "center";
    textField.setTextFormat(format);

  • Center text in JTable

    Hello!
    Could anyone help me out how center text (or left/right aligment) in JTable cells?
    Best Regards
    Staffan

    Use your own [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender]renderer?
    : jay

  • Center text in photobook

    how do I center text in a photobook?
    thank you

    JASCHI:
    Welcome to the Apple Discussions. You have to copy the text that you've entered, past it in a text editor where you can change the alignment to center, recopy and then repast into the book text field. Be sure to check the text by creating a pdf of the book before ordering to make sure it gets rendered as you want.
    Do you Twango?
    TIP: For insurance against the iPhoto database corruption that many users have experienced I recommend making a backup copy of the Library6.iPhoto database file and keep it current. If problems crop up where iPhoto suddenly can't see any photos or thinks there are no photos in the library, replacing the working Library6.iPhoto file with the backup will often get the library back. By keeping it current I mean backup after each import and/or any serious editing or work on books, slideshows, calendars, cards, etc. That insures that if a problem pops up and you do need to replace the database file, you'll retain all those efforts. It doesn't take long to make the backup and it's good insurance.
    I've written an Automator workflow application (requires Tiger), iPhoto dB File Backup, that will copy the selected Library6.iPhoto file from your iPhoto Library folder to the Pictures folder, replacing any previous version of it. You can download it at Toad's Cellar. Be sure to read the Read Me pdf file.

Maybe you are looking for