Line wrapping and scrolling in JPanel

Hello,
I've got an empty JPanel to which I want to add an (unknown) number of JLabels. Each JLabel has a text which is just one word. When my program is adding JLabels to the JPanel, I want it to have the same behaviour as a normal text editor: when a line is full, the next line gets filled (line wrapping).
If I just keep adding JLabels to a JPanel of a fixed size with .add(), there's no line wrapping. I tried it by giving the JPanel a fixed size, flowLayout and nesting it within a JScrollPane, but it keeps filling one long line, instead of jumping to the next one.
Any obvious solutions??
Thanks
Mark

well this depends on how your layout is build, you should post some code so we can see what your trying to do.
For example if your JPanel is the Frame's main panel, fixing a MaximumSize or PreferredSize wont have any effect, it will grow as big as you defined the JFrame size.
If you have only a JPanel with a max size of 200,300 in a JFrame with a size of 800,600, it will grow to 800,600.
You could create a BoxLayout with X axis, then insert an HorizontalStruts, insert your JPanel and another Horizontal Struts(Box.createHorizontalStrut(int width) ) to force the JPanel to be smaller than the JFrame.
I did not test this a lot, but it seams to work
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test {
  public static MyFrame frame ;
  public static void main(String[] args) {
    frame = new MyFrame();
    frame.show(true);
    frame.pack();
  public static class MyFrame extends JFrame {
    JLabel a, b, c, d, e, f, g, h, i, j, k ;
    public MyFrame(){
      super();
      JPanel sizeLimiter = (JPanel)this.getContentPane();
      sizeLimiter.setLayout(new BoxLayout(sizeLimiter, BoxLayout.X_AXIS));
     // sizeLimiter.setPreferredSize(new Dimension(800,600));
      JPanel mainPanel = new JPanel();
      mainPanel.setLayout(new FlowLayout());
      mainPanel.setPreferredSize(new Dimension(400,300));
      mainPanel.setMinimumSize(new Dimension(400,300));
      a = new JLabel("this is sample test ");
      b = new JLabel("to demonstrate an example ");
      c = new JLabel("of simple a flow layout ");
      d = new JLabel("which is wrapping ");
      e = new JLabel("when it reaches the end ");
      f = new JLabel("of a line. ");
      g = new JLabel("Set the maximum size of the panel ");
      h = new JLabel("And it should work ");
      i = new JLabel("If it doesnt post your code so we can");
      j = new JLabel("check it out to see whats wrong ");
      k = new JLabel("sincerly yours, Jf Beaulac ");
      mainPanel.add(a);
      mainPanel.add(b);
      mainPanel.add(c);
      mainPanel.add(d);
      mainPanel.add(e);
      mainPanel.add(f);
      mainPanel.add(g);
      mainPanel.add(h);
      mainPanel.add(i);
      mainPanel.add(j);
      mainPanel.add(k);
      // Fix some "margins"
      sizeLimiter.add(Box.createHorizontalStrut(200));
      // Squeeze the panel
      sizeLimiter.add(mainPanel);
      sizeLimiter.add(Box.createHorizontalStrut(200));
    protected void processWindowEvent(WindowEvent e) {
      super.processWindowEvent(e);
      if (e.getID() == WindowEvent.WINDOW_CLOSING) {
        this.dispose();
}Regards,
Jf Beaulac

Similar Messages

  • Line wrapping and font styles?

    Hi,
    If I have a piece of text which I would like to see line wrapped, and font styled, how should I do that?
    javax.swing.JTextArea has the capabilities to set line wrapping to on.
    javax.swing.JTextPane has the capabilities to set font styles like bold, italic and so on.
    But what if you have a piece of text you don't know the (possible) length of (so you would like to have line wrapping), AND to which you want to apply font styles to. JTextArea and JTextPane are siblings, not ancestors. So I can't use it. I have looked in the code to see if I could use pieces of code in my own program. But not luck.
    Do you have a suggestion for me?
    TIA,
    Abel

    camickr wrote:
    JTextPane wraps by default. I'm not sure what your problem is.I did not know that JTextPane did wrap. And I could not find it in the documentation.
    But thanks for the information!

  • How to use line wrapping and line spacing in java?how to use line wrapping

    how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?

    Hello,
    You should post your question at:
    http://java.forum.sun.com
    Thanks
    - Rose

  • How to use line wrapping and line spacing in java?

    how to use line wrapping and line spacing in java?

    Hi,
    This is explained in the java Tutorial. Please see the link:
    http://java.sun.com/docs/books/tutorial/i18n/text/line.html
    and find some sample examples.
    Hope this helps,
    --Sun/DTS                                                                                                                                                                                                                                                                                                                                                                                       

  • PanelGroupLayout line wrapping and af:iterator

    Hello.
    I have a collection of elements and I would like to form a layout where those elements would be horizontal in a line while they fit allowed space or wrap to another line.
    The collection elements are displayed with af:iterator.
    I thought a panelGroupLayout would do exactly what I need but instead the elements have vertical layout (each on a separate line).
    Could someone advice me please?
    Here's exactly what I need in an ADF Tag Guide: http://jdevadf.oracle.com/adf-richclient-demo/faces/components/index.jspx#%2Fcomponents%2FpanelGroupLayout.jspx
    Here's an illustration: http://img834.imageshack.us/img834/3551/wrapb.png
    JDev 11R2
    panelStretchLayout
    <f:facet name="top">
                <af:panelGroupLayout id="pgl1" layout="vertical"> <!-- outer container -->
                    <af:outputLabel value="Available" id="ol1" styleClass="header"/>
                    <af:panelGroupLayout id="pgl3"> <!-- default layout -->
                        <af:iterator id="i1" value="#{bindings.InformationMetatermsKisView1.collectionModel}"
                                     var="row" rows="-1"> <!-- collection -->
                            <af:panelGroupLayout id="pgl2" layout="horizontal" inlineStyle="border, background..." > <!-- collection element -->
                               golink and commandLink
                            </af:panelGroupLayout>
                        </af:iterator>
                    </af:panelGroupLayout>
                    <f:facet name="separator">
                        <af:spacer width="10" height="10" id="s1"/>
                    </f:facet>
                    <af:spacer width="10" height="10" id="s3"/>
                </af:panelGroupLayout>
            </f:facet>Edited by: ILya Cyclone on Apr 4, 2013 4:31 PM

    Seems like I could archieve what I wanted with CSS: default panelGroupLayout and inlineStyle or the elements = float: left; white-space: nowrap; .
    Even though everything seem to work and look good, I'm a bit nervous as it is in the end not the greatest idea to mess with ADF layout managers with pure CSS.
    Would there be some ADF-style solution?
    Take a look at what I have:
    <af:panelGroupLayout id="pgl3">
                                <f:facet name="separator">
                                    <af:spacer width="10" height="10" id="s7"/>
                                </f:facet>
                                <af:iterator id="i2" value="#{bindings.InformationMetatermsKisView1.collectionModel}"
                                             var="row" rows="-1">
                                    <af:panelGroupLayout id="pgl24" layout="horizontal"
                                             inlineStyle="float: left; white-space:nowrap; border: 1px #9dacc9 solid; border-radius: 5px; padding: 3px; background-color: #dde7f1; margin: 2px;">
                                             collection element
                                        <f:facet name="separator">
                                            <af:spacer width="8" height="8" id="s8"/>
                                        </f:facet>
                                    </af:panelGroupLayout>
                                </af:iterator>
                            </af:panelGroupLayout>

  • Line wrap.

    Hey guys, i am trying to learn how to do word wrap on Jtextareas....i found this code by surfing this site, i implemented it into my code but the line wrap had no effect.
    I think i have to set a value somewhere to say after 200chars do a line wrap and go to next line. But i cant find how to do this anywhere.
    Will anyone please tell me how to set how many chars can be on each line?
    (sorry if this question isnt specific enough, but i am stuck for aboout 2 hours on this problem)
    JTextArea textArea = new JTextArea(
        "This is an editable JTextArea " +
        "that has been initialized with the setText method. "
    textArea.setFont(new Font("Serif", Font.ITALIC, 16));
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);

    Hi guys still trying to figure out that new line thingy...I am getting close, but i have an error that i cant solve, can any see what is wrong, i have pasted the error at the end..
    here is my code:
    JTextArea resourceDescField = new JTextArea();
         JScrollPane resourceDescFieldScrollPane = new JScrollPane(resourceDescField);
    resourceDescField.getDocument().addDocumentListener(new MyDocumentListener());
            resourceDescField.getDocument().putProperty("name", "Text Area");
    class MyDocumentListener implements DocumentListener
              String newline = "\n";
              public void insertUpdate(DocumentEvent e)
                  updateLog(e, "inserted into");
              public void removeUpdate(DocumentEvent e)
                  updateLog(e, "removed from");
              public void changedUpdate(DocumentEvent e)
              public void updateLog(DocumentEvent e, String action)
                  Document doc = (Document)e.getDocument();
                  int changeLength = e.getLength();             
                   if(changeLength > 150);
                   resourceDescField.append(resourceDescField.getText()+newline);
         }here is my error:
    Exception occurred during event dispatching:
    java.lang.IllegalStateException: Attempt to mutate in notification
    at javax.swing.text.AbstractDocument.writeLock(Unknown Source)
    at javax.swing.text.AbstractDocument.insertString(Unknown Source)
    at javax.swing.JTextArea.append(Unknown Source)
    at UpdateResource$MyDocumentListener.updateLog(UpdateResource.java:191)
    at UpdateResource$MyDocumentListener.insertUpdate(UpdateResource.java:17
    6)
    at javax.swing.text.AbstractDocument.fireInsertUpdate(Unknown Source)
    at javax.swing.text.AbstractDocument.insertString(Unknown Source)
    at javax.swing.text.JTextComponent.replaceSelection(Unknown Source)
    at javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction.actionPerform
    ed(Unknown Source)

  • Drawing lines, rectangles and circles as objects onto a JPanel.

    Hi. I have to complete a task in school. The work is to create some simple 2D graphical editor. I'm new to java and I have some problems with this job, so I'm looking for help where it is possible...
    I created a JFrame and using it as a window. Into this JFrame I've added a toolbox (JToolBox) and "drawpad" - a JPanel. The toolbox wasn't any problem, but I aim to use the JPanel for drawing 2D objects. I tought about creating some container of objects, where I could put lines, rectangles or circles, each one with its properties (color, [x; y] coordinates on the scene, filling and drawing width) and then, draw this scene onto the JPanel.
    It should be something like windows Paintbrush. Can be simplier, but including the possibility to move and change properties of drawn objects.

    Well, there are two approaches to this that come to mind:
    1. Create an image. If this program is supposed to be like Windows Paint, the tools you are describing are only there for the sake of modifying a two dimensional image. In that case, I would recommend using a BufferedImage.
    The JPanel can contain a single JLabel. The JLabel is constructed in the following fashion:
    JLabel image_label = new JLabel(new ImageIcon(bufferedImage));...where bufferedImage is the image on which you will be storing the data. You can use bufferedImage.getGraphics() to get an object which will quite happily draw geometric shapes for you. Then, after each draw, you tell the panel to repaint itself.
    2. Store the shapes and create a component to draw them for you. You'd create a new JComponent class that would accept objects representing geometric shapes. You then override the paintComponent method on this new class to have it render itself according to the contents of the geometry objects. It would also probably be advisable to have all of these classes implement a common interface (which you would also create) so the rendering component could treat them identically.

  • Read Only TextAreas with Carriage Return, Line Breaks and Word Wrapping

    Hi all,
    I know there are a few posts around this subject but I cannot find the answer to the exact problem I have.
    I have a page that has a 'TextArea with Character Counter' (4000 Chars) that is conditionally read only based on the users credentials (using the 'Read Only' attributes of the TextArea item).
    When the field is editable (not Read Only) everything works fine but when I make the field Read Only I start to have problems:
    The first problem is that the Carriage Return and Line Breaks are ignored and the text becomes one continuos block. I have managed to fix this by adding pre and post element text of pre and /pre tags. This has made the Carriage Return and Line Breaks word nicely and dispaly correctly.
    However, it has introduced a second problem. Long lines, with no Carriage Returns or Line Breaks, now extend to the far right of the page with no word wrapping, making my page potentially 4000+ characters wide.
    How can I get the field to be display only, with recognised Carriage Returns and Line Breaks, and Word Wrapping inside a fixed width of, say, 150 characters?
    Many thanks,
    Martin

    Hi,
    Just a cut and paste of yours with the field name changed:
    htp.p('<script>');
    htp.p('$x("P3_COMMENTS").readonly=true;');
    htp.p('</script>');I also have the following in the page HTML Header, could they be conflicting?
    <script type="text/javascript" language="JavaScript">
    function setReleaseToProd(wpTypeCode){
       //setReleaseToProd($v(this))
      var get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=set_release_to_prod',0);
      get.addParam('x01',wpTypeCode);
      gReturn = get.get();
      if(gReturn) {
         $s('P3_RELEASE_TO_PROD',gReturn);
      get = null;
    </script>I am a long way from knowing much about Javascript (this page code was written by someone else) so all help is much appreciated.
    Martin

  • HTMLEditorKit and line wrapping

    If you feed some HTML to an HTMLEditorKit and then ask for the text back, HTMLEditorKit formats the text for you and, in particular, breaks it into smaller lines as it deems necessary. This can be very inconvenient, because you may end up with white space in unexpected places.
    Does anybody know of a way to prevent HTMLEditorKit from line wrapping?
    Here is a little program which demonstrates what I am talking about...
    import java.io.StringReader;
    import javax.swing.text.html.HTMLDocument;
    import javax.swing.text.html.HTMLEditorKit;
    public class LineWrap {
        public static void main(String[] args) {
            String text = "<html><body>This is some <b>HTML</b> text.  It is all " +
                "on a single line, unless somebody takes the initiative to wrap " +
                "it into several lines.</body></html>";
            try {
                HTMLEditorKit kit = new HTMLEditorKit();
                HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
                kit.read(new StringReader(text), doc, 0);
                kit.write(System.out, doc, 0, doc.getLength());
            } catch (Exception exc) {
                exc.printStackTrace();
    }The output looks like this:
    <html>
      <head>
      </head>
      <body>
        This is some <b>HTML</b> text. It is all on a single line, unless somebody
        takes the initiative to wrap it into several lines.
      </body>
    </html>

    I have no idea about it, but does this help?
    http://forum.java.sun.com/thread.jspa?threadID=298090
    Yes it does! You can prevent line wrapping by subclassing HTMLWriter and overriding the method canGetWrapLines() so that it always returns false.
    Thank you.

  • Multiple StringItems and line wrapping

    Hello!
    Why is it, that StringItems, that have to be line wrapped because of their length, cause the following StringItems to start at a new line after the preceding one, even if there is still enough room?
    Tested with WTK 2.5.1 (Qwerty Device)
    Here's an example:
    * ExampleMidlet.java
    * Created on 1. November 2007, 18:30
    package hello;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    * @author rp
    * @version
    public class ExampleMidlet extends MIDlet {
    public void startApp() {
    StringItem s1,s2,s3;
    Form form = new Form("Example");
    s1 = new StringItem(null,"That's just an example for a very long line, which has probably to be wrapped and a ");
    s1.setLayout(Item.LAYOUT_2);
    form.append(s1);
    s2 = new StringItem(null,"hyperlink");
    s2.setLayout(Item.LAYOUT_2);
    form.append(s2);
    s3 = new StringItem(null,", which is followed by even more Text");
    s3.setLayout(Item.LAYOUT_2);
    form.append(s3);
    Display.getDisplay(this).setCurrent(form);
    public void pauseApp() {
    public void destroyApp(boolean unconditional) {
    Some real devices do this right, starting an item where the
    preceding one stops. Unfortunately lot's of others don't (following
    the WTK)
    Please!
    Do I really have to generate zillions of One-Word-StringItems in order to avoid ugly line wrapping ?
    cheers, Roland

    Please!
    Do I really have to generate zillions of One-Word-StringItems in order to avoid ugly line wrapping ?How about just one StringItem containing the entire text? Or would that create other problems?I have text with hyperlinks in between. That's why I cannot put it in one single StringItem.
    Device fragmentation. Nothing anyone can do about it.I don't think, device fragmentation is an argument here:
    Why should there be a layout directive like Item.LAYOUT_NEWLINE_BEFORE/AFTER
    if you shouldn't also have the possibility to have no line wrap at all?
    Here's what the API says:
    A row break occurs before an item if any of the following conditions occurs:
    the previous item has a row break after it;
    it has the LAYOUT_NEWLINE_BEFORE directive; or
    it is a StringItem whose contents starts with "\n";
    it is a ChoiceGroup, DateField, Gauge, or a TextField, and the LAYOUT_2 directive is not set; or
    this Item has a LAYOUT_LEFT, LAYOUT_CENTER, or LAYOUT_RIGHT directive that differs from the Form's current alignment.
    A row break occurs after an item if any of the following conditions occurs:
    it is a StringItem whose contents ends with "\n"; or
    it has the LAYOUT_NEWLINE_AFTER directive; or
    it is a ChoiceGroup, DateField, Gauge, or a TextField, and the LAYOUT_2 directive is not set.
    Neither there's a directive, that differs from the Form's current alignment, nor there's a newline in
    the StringItem, etc.
    So I guess,there shouldn't be a row break here.
    Thanks, Roland

  • How to prevent automatic line wrapping in a JEditorPane

    I have added a JEditorPane inside a JScrollPane which is inturn is added inside a JPanel with a GridLayout.
    While JEditorPane is loaded with an HTML page or a html file is read into it with an HTMLDocument the longer lines are geting wrapped automatically to the next line when the display area of the parent component of the JPanel where the original JScrollPane is held (like the JFrame or JSplitPane etc.)
    It doesn't help even after seeing a preferredsize/maximumSize or minimumSize
    of the JEditorPane (b'cos it defaults to some other size which i'ven't set at all).
    The horizontal scrollbar apperas only the when the the JEditorPanes size is reduced lesser than its defult size which has been set (probably by the layout manager).
    I want to get rid of this behaviour of the JEditorPane such that horizontal Scollbar should apper as soon as the user reduce the size of the window displaying the above component hierarchy (parent container->JScrollPane->JEditorPane) and no line wrapping occurs.
    Note : 1. JEditorPane doesn'y have linewrapping API like JTextArea
    2. Its default and automatic linewrapping behaviour is conforming
    with word line wrapping where lines are broken at the end of a
    word which can be fully accomodated.

    I have added a JEditorPane inside a JScrollPane which is inturn is added inside a JPanel with a GridLayout.
    While JEditorPane is loaded with an HTML page or a html file is read into it with an HTMLDocument the longer lines are geting wrapped automatically to the next line when the display area of the parent component of the JPanel where the original JScrollPane is held (like the JFrame or JSplitPane etc.)
    It doesn't help even after seeing a preferredsize/maximumSize or minimumSize
    of the JEditorPane (b'cos it defaults to some other size which i'ven't set at all).
    The horizontal scrollbar apperas only the when the the JEditorPanes size is reduced lesser than its defult size which has been set (probably by the layout manager).
    I want to get rid of this behaviour of the JEditorPane such that horizontal Scollbar should apper as soon as the user reduce the size of the window displaying the above component hierarchy (parent container->JScrollPane->JEditorPane) and no line wrapping occurs.
    Note : 1. JEditorPane doesn'y have linewrapping API like JTextArea
    2. Its default and automatic linewrapping behaviour is conforming
    with word line wrapping where lines are broken at the end of a
    word which can be fully accomodated.

  • Problems with JTextPane line wrapping

    Hi to all.
    I'm using a code like this to make editable a figure that I paint with Java 2D. This JTextPane don't has a static size and for that, the text in it cannot be seen affected by the natural line wrap of the JTextPane component. The problem is that I have to set a maximun size for the JTextPane and I want to use the line wrap only when the width of the JTextPane be the maximun width. How can I do this?
    public class ExampleFrame extends JFrame {
        ExamplePane _panel;
        public ExampleFrame() {
            this.setSize(600, 600);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            _panel = new ExamplePane();
            getContentPane().add(_panel);
            this.setVisible(true);
        public static void main(String[] args) {
            ExampleFrame example = new ExampleFrame();
        public class ExamplePane extends JPanel {
            public ExamplePane() {
                this.setBackground(Color.RED);
                this.setLayout(null);
                this.add(new ExampleText());
        public class ExampleText extends JTextPane implements ComponentListener, DocumentListener,
                KeyListener {
            public ExampleText() {
                StyledDocument doc = this.getStyledDocument();
                MutableAttributeSet standard = new SimpleAttributeSet();
                StyleConstants.setAlignment(standard, StyleConstants.ALIGN_RIGHT);
                doc.setParagraphAttributes(0, 0, standard, true);
                this.setText("Example");
                this.setLocation(300, 300);
                this.setSize(getPreferredSize());
                this.addComponentListener(this);
                getDocument().addDocumentListener(this);
                this.addKeyListener(this);
            public void componentResized(ComponentEvent e) {
            public void componentMoved(ComponentEvent e) {
            public void componentShown(ComponentEvent e) {
            public void componentHidden(ComponentEvent e) {
            public void insertUpdate(DocumentEvent e) {
                Dimension d = getPreferredSize();
                d.width += 10;
                setSize(d);
            public void removeUpdate(DocumentEvent e) {
            public void changedUpdate(DocumentEvent e) {
            public void keyTyped(KeyEvent e) {
            public void keyPressed(KeyEvent e) {
            public void keyReleased(KeyEvent e) {
    }Thanks for read.

    I'm working hard about that and I can't find the perfect implementation of this. This is exactly what I want to do:
    1. I have a Ellipse2D element painted into a JPanel.
    2. This ellipse is painted like a circle.
    3. Into the circle there's a text area, that user use to name the cicle.
    4. The text area is a JTextPane.
    5. When the user insert a text area, it can increase it size, but it can't be bigger than the circle that it contains.
    6. There is a maximun and a minimun size for the circle.
    7. When the user write into de JTextPane, it grows until arriving at the limit.
    8. When the JTextPane has the width size limit, if the user writes more text into it, the JTextPane write it into another line.
    9. The size of the JTextPane has to be the optimun size, it cannot have empty rows or empty lines.
    This code does all this except 9, cause if the user remove some text of the text area, the form of the JTextPane changes to a incorrect size.
    public class ExampleFrame extends JFrame {
        ExamplePane _panel;
        public ExampleFrame() {
            this.setSize(600, 600);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            _panel = new ExamplePane();
            getContentPane().add(_panel);
            this.setVisible(true);
        public static void main(String[] args) {
            ExampleFrame example = new ExampleFrame();
        public class ExamplePane extends JPanel {
            public ExamplePane() {
                this.setBackground(Color.RED);
                this.setLayout(null);
                this.add(new ExampleText());
        public class ExampleText extends JTextPane implements ComponentListener, DocumentListener,
                KeyListener {
            public ExampleText() {
                StyledDocument doc = this.getStyledDocument();
                MutableAttributeSet standard = new SimpleAttributeSet();
                StyleConstants.setAlignment(standard, StyleConstants.ALIGN_CENTER);
                doc.setParagraphAttributes(0, 0, standard, true);
                this.setText("Example");
                this.setLocation(300, 300);
                this.setSize(getPreferredSize());
                //If it has the maximun width and the maximun height, the user cannot
                //write into the JTextPane
                /*AbstractDocument abstractDoc;
                if (doc instanceof AbstractDocument) {
                abstractDoc = (AbstractDocument) doc;
                abstractDoc.setDocumentFilter(new DocumentSizeFilter(this, 15));
                this.addComponentListener(this);
                getDocument().addDocumentListener(this);
                this.addKeyListener(this);
            public void componentResized(ComponentEvent e) {
            public void componentMoved(ComponentEvent e) {
            public void componentShown(ComponentEvent e) {
            public void componentHidden(ComponentEvent e) {
            public void insertUpdate(DocumentEvent e) {
                Runnable doRun = new Runnable() {
                    public void run() {
                        int MAX_WIDTH = 200;
                        Dimension size = getSize();
                        Dimension preferred = getPreferredSize();
                        if (size.width < MAX_WIDTH) {
                            size.width += 10;
                        } else {
                            size.height = preferred.height;
                        setSize(size);
                SwingUtilities.invokeLater(doRun);
            public void removeUpdate(DocumentEvent e) {
                this.setSize(this.getPreferredSize());
            public void changedUpdate(DocumentEvent e) {
            public void keyTyped(KeyEvent e) {
            public void keyPressed(KeyEvent e) {
            public void keyReleased(KeyEvent e) {
    }I know that the problem is into the removeUpdate method, but I have to set to the JTextPane, allways the optimun size, how can I do this?
    Thanks to all.
    Edited by: Daniel.GB on 06-jun-2008 18:32

  • 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

  • Line wrapping - JTextPane

    Hi,
    Does anyone know how to disable line wrapping in a JTextPane?
    Thanks,
    Michael

    there 2 ways of achieving it.
    1. Instead of adding the editorpane to the JScrollPane, add the JEditorPane to a JPanel(BorderLayout->CENTER) and then the JPanel to the JScrollPane. Then you can avoid the said problem
    2. JEditorPane ta= new JEditorPane(){
    public boolean getScrollableTracksViewportWidth(){
    return false;
    use this to create ur JEditorpane.
    But the problem here is that your JEditorpane width is dynamic depending on ur text size.
    so when you add it to the JScrollPane you will not c it fitting exactly into the scrollpane width.
    hope it helps.

  • Need help with JTextArea and Scrolling

    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.swing.*;
    public class MORT_RETRY extends JFrame implements ActionListener
    private JPanel keypad;
    private JPanel buttons;
    private JTextField lcdLoanAmt;
    private JTextField lcdInterestRate;
    private JTextField lcdTerm;
    private JTextField lcdMonthlyPmt;
    private JTextArea displayArea;
    private JButton CalculateBtn;
    private JButton ClrBtn;
    private JButton CloseBtn;
    private JButton Amortize;
    private JScrollPane scroll;
    private DecimalFormat calcPattern = new DecimalFormat("$###,###.00");
    private String[] rateTerm = {"", "7years @ 5.35%", "15years @ 5.5%", "30years @ 5.75%"};
    private JComboBox rateTermList;
    double interest[] = {5.35, 5.5, 5.75};
    int term[] = {7, 15, 30};
    double balance, interestAmt, monthlyInterest, monthlyPayment, monPmtInt, monPmtPrin;
    int termInMonths, month, termLoop, monthLoop;
    public MORT_RETRY()
    Container pane = getContentPane();
    lcdLoanAmt = new JTextField();
    lcdMonthlyPmt = new JTextField();
    displayArea = new JTextArea();//DEFINE COMBOBOX AND SCROLL
    rateTermList = new JComboBox(rateTerm);
    scroll = new JScrollPane(displayArea);
    scroll.setSize(600,170);
    scroll.setLocation(150,270);//DEFINE BUTTONS
    CalculateBtn = new JButton("Calculate");
    ClrBtn = new JButton("Clear Fields");
    CloseBtn = new JButton("Close");
    Amortize = new JButton("Amortize");//DEFINE PANEL(S)
    keypad = new JPanel();
    buttons = new JPanel();//DEFINE KEYPAD PANEL LAYOUT
    keypad.setLayout(new GridLayout( 4, 2, 5, 5));//SET CONTROLS ON KEYPAD PANEL
    keypad.add(new JLabel("Loan Amount$ : "));
    keypad.add(lcdLoanAmt);
    keypad.add(new JLabel("Term of loan and Interest Rate: "));
    keypad.add(rateTermList);
    keypad.add(new JLabel("Monthly Payment : "));
    keypad.add(lcdMonthlyPmt);
    lcdMonthlyPmt.setEditable(false);
    keypad.add(new JLabel("Amortize Table:"));
    keypad.add(displayArea);
    displayArea.setEditable(false);//DEFINE BUTTONS PANEL LAYOUT
    buttons.setLayout(new GridLayout( 1, 3, 5, 5));//SET CONTROLS ON BUTTONS PANEL
    buttons.add(CalculateBtn);
    buttons.add(Amortize);
    buttons.add(ClrBtn);
    buttons.add(CloseBtn);//ADD ACTION LISTENER
    CalculateBtn.addActionListener(this);
    ClrBtn.addActionListener(this);
    CloseBtn.addActionListener(this);
    Amortize.addActionListener(this);
    rateTermList.addActionListener(this);//ADD PANELS
    pane.add(keypad, BorderLayout.NORTH);
    pane.add(buttons, BorderLayout.SOUTH);
    pane.add(scroll, BorderLayout.CENTER);
    addWindowListener( new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    public void actionPerformed(ActionEvent e)
    String arg = lcdLoanAmt.getText();
    int combined = Integer.parseInt(arg);
    if (e.getSource() == CalculateBtn)
    try
    JOptionPane.showMessageDialog(null, "Got try here", "Error", JOptionPane.ERROR_MESSAGE);
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Got here", "Error", JOptionPane.ERROR_MESSAGE);
    if ((e.getSource() == CalculateBtn) && (arg != null))
    try{
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 1))
    monthlyInterest = interest[0] / (12 * 100);
    termInMonths = term[0] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 2))
    monthlyInterest = interest[1] / (12 * 100);
    termInMonths = term[1] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 3))
    monthlyInterest = interest[2] / (12 * 100);
    termInMonths = term[2] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Invalid Entry!\nPlease Try Again", "Error", JOptionPane.ERROR_MESSAGE);
    }                    //IF STATEMENTS FOR AMORTIZATION
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 1))
    loopy(7, 5.35);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 2))
    loopy(15, 5.5);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 3))
    loopy(30, 5.75);
    if (e.getSource() == ClrBtn)
    rateTermList.setSelectedIndex(0);
    lcdLoanAmt.setText(null);
    lcdMonthlyPmt.setText(null);
    displayArea.setText(null);
    if (e.getSource() == CloseBtn)
    System.exit(0);
    private void loopy(int lTerm,double lInterest)
    double total, monthly, monthlyrate, monthint, monthprin, balance, lastint, paid;
    int amount, months, termloop, monthloop;
    String lcd2 = lcdLoanAmt.getText();
    amount = Integer.parseInt(lcd2);
    termloop = 1;
    paid = 0.00;
    monthlyrate = lInterest / (12 * 100);
    months = lTerm * 12;
    monthly = amount *(monthlyrate/(1-Math.pow(1+monthlyrate,-months)));
    total = months * monthly;
    balance = amount;
    while (termloop <= lTerm)
    displayArea.setCaretPosition(0);
    displayArea.append("\n");
    displayArea.append("Year " + termloop + " of " + lTerm + ": payments\n");
    displayArea.append("\n");
    displayArea.append("Month\tMonthly\tPrinciple\tInterest\tBalance\n");
    monthloop = 1;
    while (monthloop <= 12)
    monthint = balance * monthlyrate;
    monthprin = monthly - monthint;
    balance -= monthprin;
    paid += monthly;
    displayArea.setCaretPosition(0);
    displayArea.append(monthloop + "\t" + calcPattern.format(monthly) + "\t" + calcPattern.format(monthprin) + "\t");
    displayArea.append(calcPattern.format(monthint) + "\t" + calcPattern.format(balance) + "\n");
    monthloop ++;
    termloop ++;
    public static void main(String args[])
    MORT_RETRY f = new MORT_RETRY();
    f.setTitle("MORTGAGE PAYMENT CALCULATOR");
    f.setBounds(600, 600, 500, 500);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }need help with displaying the textarea correctly and the scroll bar please.
    Message was edited by:
    new2this2020

    What's the problem you're having ???
    PS.

Maybe you are looking for

  • Filling tax amount which deviate from the calculted one

    While adding new line to a Purchasing invoice I need to fill the tax amount (which deviate from the within TaxCodeRate calculated one). For example if amount is 10 euro vatRate = 5%.  It should be possible to fill the PriceAfterVat with 110 euro with

  • Cfolder do not respond while saving redlining layer

    Hi all, We have installed Cfolder 4.0 and ECL viewer 5.1.3 for viewing and redlining DWG , jt,.stl files. I have changed or created a redlining layer, and try to exit the ECL Viewer.When I press "finish viewer session", to save the layer the applicat

  • Cannot view contingent workers and group subs in assets assignment

    Hi I need to assign assets to employees as well as contingent workers. The assignment screen in the LOV displays employees only. Is there a way to assign assets to Contingent workers or group subs Thanks Ninad

  • How do I manage where the tab-bar is displayed in Firefox 29?

    The config setting (browser.tabs.onTop set to false in about:config) is not working in Firefox 29 -- Please have the Developer Team fix this. By not correcting this, the "new" Firefox has eliminated useful features, notably, the ability to place the

  • Parallel Ledger Setup

    Here is my understanding of how Parallel Ledgers are setup within ECC 6.0.  Please let me know if there is anything wrong with my initial understanding: Define accounting principles and assign them to ledger groups.  Assignment of accounting principl