Word wrap in JList

I was wondering if I can do a word wrap with JLists.
I have this so far.
JList pizza;
DefaultListModel listPizza;
JScrollPane scrollPizza;
listPizza = new DefaultListModel();
pizza = new JList(listPizza);
scrollPizza = new JScrollPane(pizza);
This will let me scroll horizontally if the text becomes longer than the screen, but I want it to wrap around the screen. I only want to it to scroll vertically.

In the future, swing questions should be posted in the swing forum.
If I recall correctly, you can do this by making a custom CellRenderer for your JList which uses a JTextArea to do the rendering. Search the swing forum or look at the sun java tutorial for custom renderers.

Similar Messages

  • JTextArea failing proper word wrap within JList

    A JTextArea is inserted into a JScrollPane which is being rendered in a JList. Each of these JTextAreas render correctly, except the text within them does not word wrap around the whitespace.
    Example, instead of seeing
    |Testing 1 2 3    |
    |testing.         |
    ------------------we are seeing:
    |Testing 1 2 3 tes|
    |ting.            |
    ------------------I'm aware the JTextArea component may not have a chance to validate properly, since it isn't visible until it is drawn into the JList. (Note: lineWrap on the JTextArea is set to true).
    Is there anything I can do to correct this? Or am I wrong about the cause and there's another solution?

    I think you're looking for
    JTextArea.setWrapStyleWord(true);
    Normally I'd yell at you to read the API, but I
    remember having a
    hard time finding that one myself. :)Looking at the link camickr posted, I saw that in some example code and immediately checked it out. Tried it in my code, and it works.
    I'm a big advocate on the API myself, shame on me for missing it! (Glad I'm not the only one tho)

  • Resizing ListCellRenderers using JTextArea and word wrap

    Hi,
    I'm trying to create a ListCellRenderer to draw nice cells for a JList. Each cell has a one line title and a description of variable length. So, I create a custom ListCellRenderer, which consists of a JPanel containing a JLabel for the title and a JTextArea for the description. I set the JTextArea to do wrapping on word boundried and it all almost works.
    But, the list cells don't resize to accomodate the variable height of the cells. They show only 1 line for the title and 1 line for the description.
    I have seen a few threads relating to this including the article, "Multi-line cells in JTable in JDK 1.4+" in the Java Specialists' Newsletter, which seems to do a similar trick for JTables. But so far nothing I've tried works.
    Curiously, using println debugging, my getListCellRenderer method seems to get called for each cell twice while my GUI is being drawn. It looks to me like the TextUI view that draws the JTextArea seems to do the word wrapping after the first set of getListCellRenderer calls. But, it's the first set of calls that seems to establish the layout of the list.
    Any help would be appreciated. I've pulled out quite enough hair over this one.
    -chris
    package bogus;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Font;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.*;
    public class CellRendererTest {
         public static void main(String[] args) {
              final CellRendererTest test = new CellRendererTest();
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        test.createGui();
         public void createGui() {
              JFrame frame = new JFrame("Testing Bogus ListCellRenderer");
              JList list = new JList(createBogusListItems());
              list.setCellRenderer(new MyListCellRenderer());
              frame.add(list);
              frame.setSize(200, 400);
              frame.setVisible(true);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         private MyListItem[] createBogusListItems() {
              List<MyListItem> items = new ArrayList<MyListItem>();
              items.add(new MyListItem("First item", "This is a nice short description."));
              items.add(new MyListItem("Another one", "This is a longer description which might take up a couple of lines."));
              items.add(new MyListItem("Next one", "This is a ridiculously long description which is total gibberish." +
                        "Blah blah blabber jabber goo. Blither blather bonk. Oink boggle gaggle ker-plunk."));
              items.add(new MyListItem("No Desc", null));
              items.add(new MyListItem("Last one", "Boink!"));
              return items.toArray(new MyListItem[items.size()]);
         static class MyListCellRenderer extends JPanel implements ListCellRenderer {
              private JLabel title;
              private JTextArea desc;
              // hack to see if this is even possible
              private static int[] rows = {1, 2, 3, 0, 1};
              public MyListCellRenderer() {
                   setLayout(new BorderLayout());
                   setBorder(BorderFactory.createEmptyBorder(6, 4, 6, 4));
                   setOpaque(true);
                   title = new JLabel();
                   title.setFont(new Font("Arial", Font.ITALIC | Font.BOLD, 11));
                   add(title, BorderLayout.NORTH);
                   desc = new JTextArea();
                   desc.setFont(new Font("Arial", Font.PLAIN, 9));
                   desc.setOpaque(false);
                   desc.setWrapStyleWord(true);
                   desc.setLineWrap(true);
                   add(desc, BorderLayout.CENTER);
              public Component getListCellRendererComponent(JList list, Object value,
                        int index, boolean isSelected, boolean cellHasFocus) {
                   MyListItem item = (MyListItem)value;
                   title.setText(item.title);
                   if (item.description != null && item.description.length() > 0) {
                        desc.setText(item.description);
                        desc.setVisible(true);
                   else {
                        desc.setVisible(false);
                   // uncomment next line to to somewhat simulate the effect I want (hacked using the rows array)
                   // desc.setRows(rows[index]);
                   if (isSelected) {
                        setBackground(list.getSelectionBackground());
                        setForeground(list.getSelectionForeground());
                   else {
                        setBackground(list.getBackground());
                        setForeground(list.getForeground());
                   return this;
         static class MyListItem {
              String title;
              String description;
              public MyListItem(String title, String description) {
                   this.title = title;
                   this.description = description;
    }

    This seems to work
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Insets;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.text.View;
    public class CellRendererTest {
         int WIDTH = 220;
         public static void main(String[] args) {
              final CellRendererTest test = new CellRendererTest();
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        test.createGui();
         public void createGui() {
              JFrame frame = new JFrame("Testing Bogus ListCellRenderer");
              JList list = new JList(createBogusListItems());
              final MyListCellRenderer renderer = new MyListCellRenderer();
              list.setCellRenderer( renderer );
              JScrollPane listScrollPane = new JScrollPane(list);
              frame.add(listScrollPane);
              frame.setSize(WIDTH, 400);
              frame.setVisible(true);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         private MyListItem[] createBogusListItems() {
              List<MyListItem> items = new ArrayList<MyListItem>();
              items.add(new MyListItem("First item", "This is a nice short description."));
              items.add(new MyListItem("Another one", "This is a longer description which might take up a couple of lines."));
              items.add(new MyListItem("Next one", "This is a ridiculously long description which is total gibberish." +
                        "Blah blah blabber jabber goo. Blither blather bonk. Oink boggle gaggle ker-plunk."));
              items.add(new MyListItem("No Desc", null));
              items.add(new MyListItem("Last one", "Boink!"));
              items.add(new MyListItem("Ooops this one breaks things by being longer than my fixed width", "Blabber babble gibber flipper flop."));
              return items.toArray(new MyListItem[items.size()]);
         static class MyListCellRenderer extends JPanel implements ListCellRenderer {
              public JLabel title;
              public JTextArea desc;
              Color altColor = new Color(0xeeeeee);
              public MyListCellRenderer() {
                   setLayout(new BorderLayout());
                   setBorder(BorderFactory.createEmptyBorder(6, 4, 6, 4));
                   setOpaque(true);
                   title = new JLabel();
                   title.setFont(new Font("Arial", Font.ITALIC | Font.BOLD, 11));
                   add(title, BorderLayout.NORTH);
                   desc = new JTextArea();
                   desc.setFont(new Font("Arial", Font.PLAIN, 9));
                   desc.setOpaque(false);
                   desc.setWrapStyleWord(true);
                   desc.setLineWrap(true);
                   add(desc, BorderLayout.CENTER);
              public Component getListCellRendererComponent(JList list, Object value,
                        int index, boolean isSelected, boolean cellHasFocus) {
                   Insets insets = desc.getInsets();
                int rendererLeftRightInsets = insets.left + insets.right + 8;  // 8 from panel border
                int topDownInsets = insets.top + insets.bottom;
                int listWidth = list.getWidth();
                int viewWidth = listWidth;
                   int scrollPaneLeftRightInsets = 0;
                   JScrollPane scroll = (JScrollPane) SwingUtilities.getAncestorOfClass( JScrollPane.class, list );
                   if ( scroll != null && scroll.getViewport().getView() == list ) {
                        Insets scrollPaneInsets = scroll.getBorder().getBorderInsets(scroll);
                     scrollPaneLeftRightInsets = scrollPaneInsets.left + scrollPaneInsets.right;
                     listWidth = scroll.getWidth() - scrollPaneLeftRightInsets;
                     JScrollBar verticalScrollBar = scroll.getVerticalScrollBar();
                     if (verticalScrollBar.isShowing()) {
                         listWidth -= verticalScrollBar.getWidth();
                     viewWidth = listWidth - rendererLeftRightInsets;
                   MyListItem item = (MyListItem)value;
                   title.setText(item.title);
                   if (item.description != null && item.description.length() > 0) {
                        desc.setText(item.description);
                        desc.setVisible(true);
                        View rootView = desc.getUI().getRootView(desc);
                     rootView.setSize( viewWidth, Float.MAX_VALUE );
                    float yAxisSpan = rootView.getPreferredSpan(View.Y_AXIS);
                        Dimension preferredSize = new Dimension( viewWidth, (int)yAxisSpan + topDownInsets );
                        desc.setPreferredSize( preferredSize );
                   } else {
                        desc.setVisible(false);
                   title.setPreferredSize( new Dimension( viewWidth, title.getPreferredSize().height ) );
                   // uncomment next line to to somewhat simulate the effect I want (hacked using the rows array)
                   //desc.setRows(rows[index]);
                   if (isSelected) {
                        setBackground(list.getSelectionBackground());
                        setForeground(list.getSelectionForeground());
                   else {
                        if (index % 2 == 0)
                             setBackground(altColor);
                        else
                             setBackground(list.getBackground());
                        setForeground(list.getForeground());
                   return this;
         static class MyListItem {
              String title;
              String description;
              public MyListItem(String title, String description) {
                   this.title = title;
                   this.description = description;
    }

  • Webforms - Wrap Text/Word Wrap for Column Headings

    I have some member aliases that are set as my webform's column headings, but they are fairly long. Setting the column width to a custom value that fits most of the text in the heading makes the form very wide and ugly to work with. I don't see any option to Wrap Text or use Word Wrap in the column headings. Is there any way to do this?
    Thanks!

    Hi,
    I am not aware of any option which allows you to wrap the text, it may be possible customizing the [CSS |http://download.oracle.com/docs/cd/E10530_01/doc/epm.931/html_hp_admin/ch12s03.html] though to be honest I am not even sure about that and even if it was possible it would apply to all apps.
    Cheers
    John
    http://john-goodwin.blogspot.com/

  • How to word wrap within text field

    I've created a form with a text field but when filling the form out, the words don't word wrap, but merely go in a single line across the text box field. 
    When can I format the text box to word wrap?
    tks

    I have set my text fields to multi line and the text wraps but it only starts about halfway down the text box.  Please help, this is getting frustrating...

  • How can I turn off word wrap in the View Source output?

    I'm trying to extract HTML from Word and one way to do that is to save the Word file as a .htm file and then View Source in a browser and copy that. But the words are wrapped in the View Source file. I want each paragraph to be all on one line. Is there a setting for the View Source feature that will turn off word wrap?
    Once I have that done and copied into a plain text editor, I will use Search>Replace to get rid of all the stuff Word puts there and just end up with the simple paragraph tags at the end of each paragraph, all on one line.

    You can disable wrapping and syntax highlighting in the View menu in the Edit > View Source window.

  • Looking for a word processor without word wrap, text edit doesn't cut it

    I'm looking for a word processor without word wrap, text edit doesn't work. In text edit, it automatically scoots my text over to the next line but I just want it to keep going with a horizontal scrollbar. Is there a text editor I can download from the app store or can I get textedit to work somehow where it uses a horizontal scroll bar instead of entering text to the next line?

    Hi,
    thought TextWrangler can do it.
    But it seems that the 'no word-wrap' "feature" isn't that much wanted anymore.
    Maybe one of these http://www.macupdate.com/find/mac/text%20editor can do it.
    Regards
    Stefan

  • 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

  • Word Wrap with a Vertical Grid

    I've got a vertical grid with my headers in the left column and descriptive text in the column immediately to the right.  I'd like to have the descriptive text word wrap but checking the word wrap box on the layout tab doesn't seem to have any effect.
    Any ideas?  I'm using 11.5 SP3

    I'm not sure if it will work with the iGrid in a vertical orientation, but have you tried setting the RowHeight to something like 20 or 30 instead of the default of 0?  This setting will auto adjust the grid lines based upon the font-size, but you may need to force it to a certain height in order for the wrapping to work.
    Regards,
    Jeremy

  • Word wrap with jLabel

    Is it possible to word-wrap text in a jLabel field? If not, what would be a good choice of component?

    displayArea.setLineWrap (true);
    displayArea.setWrapStyleWord (true);I thought it wasn't added automatic.
    Kind regards,
      Levi

  • How to make items in a list word wrap as needed and be variable heights

    I am trying to build a custom itemrenderer for the List control.  The items in the list are variable lengths of text, some of the text items will have different colors determined at runtime base on some criteria (this works fine now with my custom itemrenderer).  What I need is for the items to word wrap, and therefore for the list to display items of varying heights.  Is this possible to do?  All my attempts seem to have failed.  If I can't do this with an item renderer any suggestions about how to do this?  Thanks very much in advance to any of you gurus who are able to help me.

    Trick here is not to specify any height for the renderer so that Flex will determine the height according to the content. Also set the variableRowHeight="true"
    Here is a simple example
    <mx:ArrayCollection id="dp">
            <mx:Array>
                <mx:Object label="some very long text"/>
                <mx:Object label="some very loooooooooooooooooooooooooooooooooong text"/>
                <mx:Object label="some very loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong text"/>
                <mx:Object label="some very looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong text"/>
                <mx:Object label="some very long text"/>
            </mx:Array>
        </mx:ArrayCollection>
        <mx:List dataProvider="{dp}" variableRowHeight="true">
            <mx:itemRenderer>
                <mx:Component>
                    <mx:Canvas width="100%">
                        <mx:Text width="100%" text="{data.label}"/>
                    </mx:Canvas>
                </mx:Component>
            </mx:itemRenderer>
        </mx:List>

  • Force word wrap in JTextPane (using HTMLEditorKit)

    Hi!
    I have a JTextPane on a JScrollPane inside a JPanel. My text pane is using HTMLEditorKit.
    I set the scrolling policies of my JScrollPane to: JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED & JScrollPane.HORIZONTAL_SCROLLBAR_NEVER.
    I did not find in JTextPane�s API any relevant property I can control word-wrapping with (similar to JTextArea�s setLineWrap) and I have tried a few things to force word-wrapping but nothing worked...
    What happens is my text is NOT being wrapped (even though there is no horizontal scrolling) and typed characters (it is an enabled editable text componenet) are being added to the same long line�
    I�d like to force word-wrapping (always) using the vertical scroll bar whenever the texts extends for more then one (wrapped) line.
    Any ideas?
    Thanks!!
    Message was edited by:
    io1

    Your suggestion of using the example only holds if it fits the requirements of the featureDid your questions state anywhere what your requirement was?
    You first questions said you had a problem, so I gave you a solution
    You next posting stated what your where currently doing, but it didn't say it was a requirement to do it that way. So again I suggested you change your code to match the working example.
    Finally on your third posting you state you have some server related issues causing the requirement which I did not know about in my first two postings.
    State your problem and special requirments up front so we don't waste time quessing.
    I've used code like this and it wraps fine:
    JTextPane textPane = new JTextPane();
    textPane.setContentType( "text/html" );
    HTMLEditorKit editorKit = (HTMLEditorKit)textPane.getEditorKit();
    HTMLDocument doc = (HTMLDocument)textPane.getDocument();
    textPane.setText( "<html><body>some long text ...</body></html>" );
    JScrollPane scrollPane = new JScrollPane( textPane );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.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • JOptionPane.showMessageDialog() - word wrapping exceptions?!

    Hey ppl,
    Probably a silly question...
    I'm currently working with JDBC, and SQLexceptions can be very long! Currently displaying them in a JOptionPane.showMessageDialog() (as i guess most people do?), but being so long they cause it to span the whole screen & then some!
    I looked through the JOptionPane API, but didn't spot anything that might help. Is there a way to get this exception to dispaly on multiple lines, kinda like word wrap in notepad?
    Cheers for any suggestions.
    Jim

    I can't speak for other developers..But as for myself, I rarely if ever print error messages to the JOptionPane. Almost always, I print my error messages and the stack if necessary, to the ouput. This is either a command line window, console, log file, or output screen in an ide depending upon how you program. My code looks something like this.
    catch(Exception e)
        System.out.println(e.getMessage());  // Will print only the message property of the exception
        e.printStackTrace();  // Will print the stack for more information
    }Sorry I couldn't answer your question directly. Maybe someone else can. Hope I was helpful anyway.

  • JEdtiorPane/HTMLEditorKit word wrapping problems

    Hi,
    I have a JFrame component that has a splitPane, on the left side is a JTree and the right side has a JEditorPane that has it's content updated with HTML using a method to generate the HTML via the setText() method . (no url, and no html file)
    The searching I did indicates that word wrapping is the default behavior, and I saw a lot of posts from people trying to get rid of the word wrapping, but it isn't wrapping at all for me. I get the horizontal scroll bar.
    I had the same problem using a JTextPane...anyone know how to wrap text?
    here's the relevant code:
    descriptionPanel = new JPanel(new BorderLayout());
              descriptionEditorPane = new JEditorPane();
              HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
              descriptionEditorPane.setEditorKit(htmlEditorKit);
              descriptionEditorPane.setSize(new Dimension(610,800));
              descriptionEditorPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              descriptionPanel.add(descriptionEditorPane);

    Did you place the components into scroll panes and then put those into the split pane?
    If so, then I guess that calling setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) on the editor pane's scroll pane might solve your problem.

  • DataGrid, HTML Text, and WORD WRAPPING

    I have a datagrid, with 2 columns:
    - comment
    - date
    The dataprovider that feeds the datagrid is an array
    collection, with each object containing the following fields:
    - comment
    - date
    - viewed
    What I want to do is BOLD the comment cell if the comment has
    not yet been viewed. What I first tried doing was to just insert
    the <b></b> tags on the server and then feed them up to
    Flex. So here's the code that I had tried to do this with:
    <mx:DataGridColumn>
    <mx:itemRenderer>
    <mx:Component>
    <mx:HBox>
    <mx:Label htmlText="{data.comment}" />
    </mx:HBox>
    </mx:Component>
    </mx:itemRenderer>
    </mx:DataGridColumn>
    This works, but I lose the word wrapping for long comments (I
    have wordwrap="true" defined on my DataGrid).
    Then I tried changing my approach and doing something a
    little more simple to try and preserve the word wrapping, like
    this:
    <mx:DataGridColumn dataField="comment" width="100"
    wordWrap="true" fontWeight="{(data.viewed==0 ? 'bold' : 'normal')}"
    />
    Yet that doesn't seem to work either, it appears to just
    completely ignore everything... no bolding whatsoever.
    So my question is: what's the best to to control the BOLDING
    of a DataGrid cell while at the same time retaining the word wrap
    features?
    Thanks,
    Jacob

    <mx:DataGridColumn>
    <mx:itemRenderer>
    <mx:Component>
    <mx:HBox>
    <mx:Label htmlText="{data.comment}"
    wordWrap="true" height="100%"/>
    </mx:HBox>
    </mx:Component>
    </mx:itemRenderer>
    </mx:DataGridColumn>
    You might also have a little more luck working with a
    TextArea

Maybe you are looking for