Aligning text in a JtextPane

I am trying to display text in a JTextPane. I want to be able to change the background color, the foreground color and the border (color and width). Furthermore, I need multiple lines of text, and later I might want to change the font too. The text need not be editable. All this works ok with a JTextPane, except the alignment of the text. The text is always left-aligned. So the question is: what can I do to center the text in a JTextPane?
Thanx in advance.

Try somthing like this then
import javax.swing.JFrame;
import javax.swing.JLabel;
public class TestHTMLLabel {
public static void main(String[] args) {
JFrame frame= new JFrame("HTML Label");
JLabel lbl = new JLabel("<html><p align=\"left\"><B>Thanx</B> for the reply, but I am really looking for a much simpler solution. Let me rephrase my question: I want to display a rectangular area on the screen that displays wrapped text within that rectangle. I also want to be able to change the colors (<font color=\"red\">foreground</font> and background) and the border (width, color and style). The text need not be editable<p></html> ");
frame.getContentPane().add(lbl);
frame.setSize(300,300);
frame.show();
Goodluck...

Similar Messages

  • Aligning text in JTextArea

    Hi,
    Does anyone know how to set the point at which text in displayed in a JTextArea using the setText() method. I am trying to align text in the centre of a JTextArea. Is there a way one can find the pixel at the centre of the textarea and then somehow set the cursor point to the centre and to align the string correspondingly?

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class PlacingText {
      static int hInset = 20;
      public static void main(String[] args) {
        String text = "public class JTextPane \n" +
          "extends JEditorPane \n\n " +
          "A text component that can be marked up with attributes that are represented " +
          "graphically. You can find how-to information and examples of using text panes " +
          "in Using Text Components, a section in The Java Tutorial. \n\n" +
          "This component models paragraphs that are composed of runs of character level " +
          "attributes. Each paragraph may have a logical style attached to it which " +
          "contains the default attributes to use if not overridden by attributes set on " +
          "the paragraph or character run. Components and images may be embedded in the " +
          "flow of text.";
        final JTextArea ta = new JTextArea(10,40);
        ta.setMargin(new Insets(10,hInset,10,hInset));
        ta.setLineWrap(true);
        ta.setWrapStyleWord(true);
        ta.setText(text);
        JPanel panel = new JPanel();
        panel.add(new JScrollPane(ta));
        final JButton moreButton = new JButton("more");
        final JButton lessButton = new JButton("less");
        ActionListener l = new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            JButton button = (JButton)e.getSource();
            if(button == moreButton)
              hInset += 10;
            if(button == lessButton)
              hInset -= 10;
            ta.setMargin(new Insets(10,hInset,10,hInset));
            ta.repaint();
        moreButton.addActionListener(l);
        lessButton.addActionListener(l);
        JPanel southPanel = new JPanel();
        southPanel.add(new JLabel("horizontal margin:"));
        southPanel.add(moreButton);
        southPanel.add(lessButton);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(panel);
        f.getContentPane().add(southPanel, "South");
        f.pack();
        f.setLocation(300,300);
        f.setVisible(true);
    }

  • Aligning Text in Center of JTextArea

    This is a part of my previous question.
    Is there a way of aligning text, left-center-right in the JTextArea.
    Someone had mentioned JTextPane for aligning Text in the center. What is the code for this?
    Thanks again for your help.

    I'm sorry. I am new at Java so some of these concepts that may be clear to you aren't as obvious to me.
    I inserted the code as you instructed. However, I am not sure if I have to include something else.
    Please advise:
    import javax.swing.*;
    public class HelloClassTwoLine
    public static void main(String args[])
    JTextArea outputTextArea = new JTextArea(); //Create listbox object
    JScrollPane scroll= new JScrollPane(outputTextArea); //create vertical scroll object
    ===> added to original code JTextField textField=new JTextField();
    ===> added to original code textField.setHorizontalAlignment(textField.CENTER);
    outputTextArea.setText("Hello, This is Java 374\n" + //set text in list box
    "This is Java 374 with Ravi");
    JOptionPane.showMessageDialog(null, scroll, //text is argument in JScrollPane object
    "Java Program #2", JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);
    thank you again for your help
    }

  • How can I align text in Acrobat 8.1 Professional?

    Okay this is quite silly, but seriously how can I align text in adobe acrobat? I could not find a way other than creating a new document file which allows me to use alignment options automatically (example below), however does not allow me that when I reopen the same file (alignment and text options just dissapear on the bars, funny). Help anyone please? =/
    http://img152.imageshack.us/my.php?image=examplemo2.jpg

    Not that silly; but you ideally shouldn't be trying. Although there are some rudimentary (and sometimes unpredictable) editing tools in Acrobat, (I presume you are trying with the TouchUp Object tool as well as the TouchUp Text ?) much better to get it right in the source application and think of the pdf as what it basically is...a print.
    For whatever reason, v5 could edit text positioning rather more easily than the later versions.

  • Problems Aligning Text in Headers and Footers

    I have tried to add headers and footers to documents and the  alignment is wrong.  The center footer/header should be center-aligned  and the right header/footer should be right-aligned.  Unfortunately,  they are both left-aligned.
    The preview shows the headers and footers aligned correctly, but when  the headers/footers are inserted in the document, the alignment reverts  to left aligned, although it is centered and on the right side of the  page, as appropriate.
    This is not a problem in Acrobat 7.
    Please advise if this is a bug and is awaiting an update, or if there is  something that I need to do to fix this problem.
    This is a screen shot of the preview windowindicating the proper alignment as indicated in the ovals:
    Here is the actual document once the header and footer are added.  Notice how the alignment switches to flush left:
    Any guidance is appreciated.
    Thanks.
    - James

    Nope.  The good folks at Adobe have neither addressed this issue (and I have
    heard from others that it is a problem for them as well) nor have they been
    very good about maintaining my account to be able to log in and follow up on
    it.
    The truth of the matter is that it appears to be a glitch in some, but not
    all, versions of this product and clearly it is not a big enough problem for
    them to want to fix it.
    I wind up using Acrobat 7 when I need properly formatted headers and footers
    or ‹ and this ought to get the attention of the folks at Adobe and maybe
    prompt someone (anyone!) to take a look and fix this glitch ‹ you should
    check out PDFPen.  It does much of what Adobe can do including headers and
    footers.
    If I didn't already have Acrobat 7 (and 8 and now 9), I would ditch Acrobat
    and just use Preview or PDFPen.
    - James
    From:  superfluities1 <[email protected]>
    Reply-To:  <[email protected]>
    Date:  Tue, 04 Jan 2011 12:11:19 -0700
    To:  "James A. Sarna, Esq." <[email protected]>
    Subject:  Problems Aligning Text in Headers and Footers
    Anybody ever solve this problem? I just started using(trying too, that is)
    Acrobat Pro for writing letters and starting at the top I ran right into
    this problem. Seems like a deal killer.

  • How to align text at the top and bottom of a cell?

    I'm making a periodic table and need help with aligning text at the top and bottom of a cell. I'll have a picture in the middle of the cell with text above and below the pic. Thank you in advance for any kind of suggestions you can give me.

    It sounds as though you want to have 3 separate items inside of a single cell; text at the top of the cell, text at the bottom of the cell, and then a picture in the middle of the cell.  I am no expert, but to my knowledge that is not possible (someone please correct me if I am wrong.)  I also cannot figure out how to put a picture inside of a cell itself.
    I do have a way to accomplish the end result so long as what you need is the final look and not a useable table in numbers.
    Create 2-3 cells for each element.  (The middle cell, unless you can put pictures in a cell and I don't know, would just be there for peace of mind, but would hold the picture if you can, I would just do two if the pictures are to be in front of the cell anyway.)  The top cell align text to top on the Text tab of the inspector.  The bottom cell, align text to bottom on the same tab.  Then place the picture in the middle.  Now, you have what you want except there is one or two lines dividing the cells.  To get rid of this, either click the middle cell if you have one, or the top or bottom cell.  Click on the Cell tab of the inspector.  Select the bottom border and/or top border button and select "No Border" under border styles.  To make this fast, select a full row at a time, or use command click to select all of the same type of rows (middle, top, or bottom) and change all cells at once.
    I hope this helps.  Best of luck!
    ~Bret

  • How to align text to another text box

    I am very new to Indesign and I am signed up to Lynda.com so watching few a lot of tutorials, that said I need help with aligning text.
    I have a text box that is 100mm across. It has text centered. "£5"
    then above this I have in a smaller font saying "from"
    from
    £5
    I need to get the "f" of from to line up with the beginning of the £ sign? So that If I change the price to £500 the from sticks to the "£" Sign.
    To explain again the from needs to align to the left of the centred text.?
    Hope that make sense?
    Matt

    This can be done by putting the "from" text into a custom positioned anchored object just before the £ sign. You'll need to set the X coordinate relative to the anchor, and adjust the offset on both x and y to get the positioning where you want it.
    I'm sure there are lessons on Anchored Objects on Lynda.com.

  • How to align text(left, right or center) on a button?

    I can not figure out how to align text on a button,
    could someone help me out?
    Thanks in advance

    JButton btn=new JButton("hi");
    btn.setHorizontalAlignment(int i)
    i=0 center
    i=2 left
    i=4 right

  • How to Align Text in the TextArea

    How to Align text in the TextArea. My purpose is that I want to post the records after retrieving from database. All the records in each fields should keep aligned like Oracle WorkSheet.
    I want this way
    Code Name Place City
    a01 nilopher swiss street japan
    a02 rozina lovely street aus
    a03 benazir king's camp pitsburg
    and the out put should not look like this :-
    Code Name Place City
    a01 nilopher swiss street japan
    a02 rozina lovely street aus
    a03 benazir king's camp pitsburg
    here place and city records are getting disturbed accordingly the length of name.

    Well, first off (if it's not default, that is) you must set a monospaced font on the TextArea, unless you want to count pixelwidth of each and every string and then do an estimate on how many fill blanks you want...
    If you have the each string as a line, you use a StringTokenizer on it, extract each token, put all the tokens for that line into an array of strings.
    When every line is done, you compare the length of the nth String of each array and save the highest numbers.
    Then you reassemble each line from the arrays and pad in spaces where the tokens are too short.
    HTH,
    Fredrik

  • Cannot Align text in cell

    Greetings,
    I am having issues when trying to format my spreadsheet.  First of all, I have "Wrap Text in Cell" option turned on.  So when I have text that can fit into the cell, its fine.  But when I have long text in the cell, it wraps the text in the cell so it can fit inside, which I'm fine with.... but for some reason, it is not aligning it in the cell properly, so now part of the text it cut off.  I try to center align the text, but no use. I hit the button for "Align text in the middle of the table cell", and still does not align the text so that its centered, not cut off. I have included an image of what im talking about. Help please?

    Hello
    Here is what I get with Times New Roman under 10.6.8
    May you try to
    quit Pages
    trash the preferences file :
    <startupVolume>:Users:<yourAccount>:Library:Preferences:com.apple.iWork.Pages.pl ist
    restart Pages
    It it changes nothing, try to :
    quit Pages
    trash the preferences file :
    <startupVolume>:Users:<yourAccount>:Library:Caches:com.apple.iWork.fonts
    restart Pages
    Yvan KOENIG (VALLAURIS, France) mercredi 24 août 2011 21:24:52
    iMac 21”5, i7, 2.8 GHz, 4 Gbytes, 1 Tbytes, mac OS X 10.6.8 and 10.7.0
    My iDisk is : <http://public.me.com/koenigyvan>
    Please : Search for questions similar to your own before submitting them to the community
    To be the AW6 successor, iWork MUST integrate a TRUE DB, not a list organizer !

  • Is it possible to use tabs to right align text in Muse, as you can in InDesign?

    Can I use tabs to right align text in Muse, as you can in InDesign?
    I have a beauty treatment followed by a price and I want to right align the price, keeping the treatment on the left of the text box.
    Thank you!

    For what would typically be a two column tab stop layout, I'd generally use inline text frames and the Wrap panel.
    Put the price in it's own text frame. Then cut and paste the text frame BEFORE the item name so it's an inline text frame within the text frame containing the descriptions.Using the Wrap panel set it to float to the right. Then select it and set the right offset so it floats outside the right side of the original text frame.
    Start with this.
    Cut and paste the text frame at the start of the item paragraph.
    Choose the third icon in the Wrap panel to cause the item to float to the right of the text frame.
    Turn off the lock for the 4 wrap offset values.
    Adjust the right offset to a negative value so the item is outside the text frame to the right (to wherever you want it).
    Repeat the same steps above for the other items.
    Note that once it's set up this way you can freely edit the descriptions or change the width of the original text frame and the prices will adjust accordingly. This will also result in things lining up in the browser even if the text layout engine of a specific browser line breaks the text differently.
    This approach is tedious, but the end result will continue to line up as you make changes in Design view and will line up in every browser/OS/device.
    Someday Muse will support tables, which would be the more natural way to achieve this style of layout on the web. Until then, inline items with wrap is usually the best approach for this type of two column layout.

  • Align text between columns with space after paragraphs.

    I am creating a proposal with a ton of text. I used to align everything to a baseline grid with justified type and indented paragraphs. Recently, however, I was asked to change the style to left aligned text with spaces between the paragraphs. The text flows into two columns per page, but I'll be damned if I can get the text to line up. I've tried different baseline grids as well as before and after spacing. I think my issue might be trying to keep paragraph spacing as half the leading. If my copy text leading and baseline are 14 or 7 pt, will a 7 pt paragraph space after work?
    My leading and pt size is below, if anyone can point me to a solution.
    Body copy: 9 pt font/14 pt leadingSpace before/after: 3.5/3.5
    Subheaders: 10 pt font/ 14 pt leadingSpace before/after: 7/3.5
    Baseline: tried both 14 pt and 7 pt

    That's what I thought. I was taught to either have an indented second paragraph or to separate the paragraphs by half the leading of the type. Seems like it's impossible to align the text that way. A full leading separation (14 pt) between paragraphs seems excessive though.

  • Inserting text from one JTextpane to another

    How do i insert text from one jTextpane to another with the attributes i used in the first. Please help.

    i'm using a defaultstyleddocument. Also.....if u know
    how i can transfer this data through a
    DataOutputStream to another computer.Hi again,
    DefaultstyledDocument uses a tree-structure with classes in it, that implements the Element-Interface to hold the styles. It is very easy to get the plain text, but what you need to transfer a part of text from one JTextPane with DefaultStyledDocument in it to another with the same document-style in it, is a sequence of (string, AttributSet) - pairs, so you are able to insert them in the destination document by the insertString(...)-method.
    It is easy to get the Element by postion from the document and retrieve the Attributset from it that it uses in that position. I guess, an approach would be, to do the following:
    get the Attributset at the start of the text = AttributSet of the pair
    scan the document until the set changes
    extract the string from start to the position right before the set changes = string of the pair
    store the (String,AttributSet)-pair in a Vector
    do this in the same way, but this time the "start" will be the position of the start of the new Attributset that causes the end of the scan above.
    When this is done for the hole text, that is to be transferred, you have a Vector with the String-AttributSet-pairs that you can use to insert them in the other JTextPane by calling the
    insertString(...)-method with this values.
    Tell me, what you are thinking about that - I don't know another method for this and had to create a solution on the fly for you, so that is perhaps not the best way to do it.
    greetings Marsian

  • Aligning text in JLabel

    Hi all,
    I'm simply trying to align text in a JLabel.
    I've been trying to use HTML formatting inside the JLabel, e.g:
    label = new JLabel (" <HTML><CENTER><P>Line one</P> <P>Line two</P></CENTER> </HTML>" );but when I try to use the <CENTER> tag it seems to be ignored?
    Why?
    How do I get around this?
    Many thanks.

    You can use the following code segment:
    JLabel ab = new JLabel("GG" ,  SwingConstants.CENTER);Hope it helps.
    --DM                                                                                                                                                                                                                                                                       

  • Aligning text in a text area

    Is it possible to align text in a JTextArea?

    also not sure what you're after, but try this
    import javax.swing.*;
    import java.awt.*;
    class Testing extends JFrame
      public Testing()
        setLocation(300,200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        String[] name = {"joe","christopher","fred","robert","al","josephine","mary"};
        String[] income = {"100","100000","10000","1","88888","50000","200000"};
        JPanel jp = new JPanel();
        JTextArea ta = new JTextArea(20,30);
        JScrollPane sp = new JScrollPane(ta);
        sp.setPreferredSize(new Dimension(175,150));
        jp.add(sp);
        getContentPane().add(jp);
        pack();
        String pad = "                    ";
        ta.setFont(new Font("monospaced",Font.PLAIN,12));//comment out this line to see difference
        for(int x = 0; x < name.length; x++)
          ta.append(name[x]+(pad+income[x]).substring(name[x].length()+income[x].length())+"\n");
      public static void main(String[] args){new Testing().setVisible(true);}
    }

Maybe you are looking for