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;
}

Similar Messages

  • 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

  • How can I use excel and word on the IPAD2

    How can I use excel and word documents on my Ipad 2

    There are apps such as Documents To Go which support reading/editting/creating those sorts of documents :
    standard version  -  http://itunes.apple.com/us/app/documents-to-go-office-suite/id317117961?mt=8
    premium version  -  http://itunes.apple.com/us/app/documents-to-go-premium-office/id317107309?mt=8

  • What can i do my computer freezes when i use safari and word document?

    My computer freezes when I am using Safari and word document. Can some help me??

    The same thing just happened to my new ipod today while i was trying to use an app. A lot of people say that it is caused by an ios update, but I let the battery on my ipod drain until it turned off.  Once i charged it, it turned on and is working normally again

  • I need to open and use Excel and Word files on my iPad, which software need to get?

    I need to open and use Excel and Word files on my iPad, which software need to get?

    The options include :
    Apple's Pages app for Word docs and Numbers for Excel spreadsheets
    There are also third-party apps which support both word and excel in the one app e.g.Documents To Go and QuickOffice HD

  • Text area and Word Wrapping

    I am creating a email form and am having problems with word
    wraping in the text area. You can view the page and the output if
    you put your email address in the form. The problem is the text
    areas word wrap when inputting your information but all formatting
    is lost in the email. Even if I add spacing for paragraphs. All
    data is just a big run on sentence.
    Here is the
    Page.
    I am using Dreamweaver * and php.
    Thanks

    Someone may have tried this because I received this output in
    an email. You can see the formattint is lost.
    Gear Ad:
    Description:
    This is a test. Line 1 Line 2 Line 3 Line 4 -
    Test...test...test...test...test...test...test...test...test...test...test...test...test. ..test...test...test...test...test...test...test...test...test...test...test...test...test ...done!
    Price:
    test
    Contact:
    This is a test.

  • [Solved]Conky and word wrapping - Is there a way?

    So I have a very limited area to work with, something like 176x360 (+/- a few pixels), and I want the ability to show an RSS feed. Well, the feed works of course, but due to the limited width, I'm in great need of word wrapping, and for that problem I have found no solution and going on for 2-3 hours straight, my head hurts
    Anyway, here's my .conkyrc, not that it's needed of course.
    # ~/.conkyrc
    double_buffer yes
    use_xft yes
    xftfont Bitstream Vera Sans Mono:size=8
    xftalpha 0.8
    update_interval 1.0
    total_run_times 0
    own_window yes
    own_window_type override
    own_window_transparent yes
    own_window_colour hotpink
    own_window_hints undecorated,below,skip_taskbar,sticky,skip_pager
    minimum_size 176 360
    maximum_size 176 360
    maximum_width 176
    draw_shades no
    draw_outline no
    draw_borders no
    stippled_borders 0
    border_margin 0
    border_width 0
    default_color green
    default_shade_color green
    default_outline_color green
    alignment bottom_right
    gap_x 16
    gap_y 16
    no_buffers yes
    uppercase no
    TEXT
    $alignc${nodename}
    $alignc${sysname} ${kernel}
    $hr
    CPU:$alignr$cpu% ${cpubar 10,106}
    RAM:$alignr$memperc% ${membar 10,106}
    HDD:$alignr${fs_used_perc /}% ${fs_bar 10,106 /}
    BAT:$alignr${battery_percent}% ${battery_bar 10,106}
    $hr
    Download: Upload:
    eth0 ${downspeed eth0} $alignr${upspeed eth0}
    wlan0 ${downspeed wlan0} $alignr${upspeed wlan0}
    $hr
    ${alignc}ARCH NEWS
    ${rss http://www.archlinux.org/feeds/news/ 1 item_titles 10 }
    I know this looks confusing and probably is full of critical error, but that simple because I'm a conky noob. I basically just downloaded a profile I liked and completely changed it over the course of a few hours.
    Anyway, I'm rambling again, but if you've got any idea's, please do let me know.
    Best regards.
    Last edited by zacariaz (2012-08-27 17:19:35)

    Okay, so I've found sort of a solution to part of the problem, so what I have so far look like this:
    wget -quiet -O - archlinux.org/feeds/news/ | fmt -w 25 -g 25
    It works as long as there are no words longer than 25 character, which I should think is rare, even including package names and such.
    However there's still the issue parsing the xml so I get only what I want:
    <item><title>$content</title><link>
    This may be solved using some sort of terminal rss parser, but I would rather prefer not to.
    Then there's the issue with reloading.
    My current conky is set to reload every second, but of course one can't just pull the feed every second and I'm not convinced that conky has any built in solution for that problem. Of course I can always start a cronjob and save it all to a file, but portability would be nice.
    anyway, I'll return later.

  • Oops alv no_zero and 'word wrap' in fieldcatalog

    Hi All,
    I have 2 queations
    1)  Can I have word wrap option in alv, ie any option to display the same cell information in multiple lines and
    2) I am trying to use no_zero of fieldcatalog as shown in below code
        wa_billets_fcat-fieldname = 'ACTUAL_QTY'.
        wa_billets_fcat-inttype  = 'C'.
        wa_billets_fcat-outputlen = '13'.
        wa_billets_fcat-coltext   = 'Actual Qty'.
        wa_billets_fcat-seltext   = 'Actual Qty'.
        wa_billets_fcat-edit      = 'X'.
        wa_billets-no_zero         = 'X'.
        APPEND wa_billets_fcat TO billet_fcat.
        CLEAR wa_billets_fcat.
    but it is giving the error as bellow
    Field "WA_BILLETS-NO_ZERO" is unknow. it is neither is one of the specified tables nor defined by a 'DATA" statement.
    Please help me
    Thanks in advance.

    hi check this....
    wa_billets_fcat-fieldname = 'ACTUAL_QTY'.
    wa_billets_fcat-reptext_ddic = 'Actual quantity'.
    wa_billets_fcat-no_zero = 'X'.
    APPEND wa_billets_fcat TO billet_fcat.
    CLEAR wa_billets_fcat.
    hope this will help for the word wrap..
    http://www.sap-img.com/fu037.htm
    regards,
    venkat
    Edited by: venkat  appikonda on May 10, 2008 4:46 PM

  • 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

  • Prob with fixed column widths and word wrapping in viewer

    i have a report where each record has a very long paragraph of text in it.
    In desktop and plus, the text column is at a fixed width and the text just wraps nicely according to the column width.
    But in Viewer, the column widths do not stay fixed, the text does not wrap, and the long text is displayed in a single line that completely stretches the column width off the page and requires a horizontal scroll bar.
    is there anyway to fix the column width in viewer, have the text naturally wrap, and prevent the column stretching. All word wrapping settings are on, but seem to have no effect. I can't seem to find any solution to this.
    Thanks...

    Hi Pritam,
    Per my understanding that you can't see the vertical scrollbar of the ReportViewer controls 2012 to scroll for the grid rows, but can see the vertical scrollbar of the web application, you also can't fix the headers while scrolling, right?
    I have tested on my local environment and can't reproduce your issue, but you have an alternative way to add some css  to the web form's source code to display the vertical scrollbar.
    Details information below for your reference:
    Please check below properties setting of the reportviewer which control the visibility of the scrollbar:
    AsyncRendering="true"
    SizeToReportContent="false"
    Please check if this problem also occur on other version of IE and other type of browser.
    Please check if you have done correct setting of the Fix data to freeze the table header as the step of below:
    http://technet.microsoft.com/en-us/library/bb934257(v=sql.100).aspx
    If step1 doesn't work, please click the source of webform.aspx and add below CSS to add the vertical scrollbar manually:
    #ReportViewer1 {
              overflow-y: scroll;
    Run the application you will see it display as below:
    Similar thread for your reference:
    https://social.msdn.microsoft.com/forums/sqlserver/en-US/f96b3b56-e920-411b-82ea-40467c922e66/reportviewer-control-vertical-scroll-bars
    If you still have any problem, please feel free to ask.
    Regards
    Vicky Liu

  • Images resizing when using drag and drop

    We just recently got PS Elements 7. I have a blank image that is sized at 600 x 1662 pixels. When I want to put a photo into that blank, I make sure that the photo is 600 pixels high. With 6, what I used drag and drop from the bin, the photo fit perfectly. With 7 it is apparently resizing the photo and I have to stretch it to fit. Is this something that I have set wrong?  If I am making sure that both items should fit together based on number of pixels, why is one changing size? Something has to be changing size or the items would fit together. I am assuming that something is set wrong, because this just does not strike me a something that should happen, or the program is not a very efficient photo editor. If necessary I will go back to 5.0, although there are things that I like better in 7.
    jean @ buffaloworks

    I'm frankly surprised you had success with this in PSE 6, since the past two versions create a special kind of smart object from images dragged up from the bin. You can use copy/paste to create a regular layer, or you can drag down to a thumbnail in the bin from an open image, but the project bin doesn't let you drag up anymore, by design.
    Did you mean to say PSE 5 rather than 6? It worked normally there.

  • HTML file and Word Wrap

    hi,
    i am saving a HTML file (downloaded from the web) ....
    i wanna know... how to set a Word Wrap... so it won't scroll to the right hand side....
    any ideas

    ok i think code will give you a better view of what i am trying to say
    try {
    URL hostURL = new URL("http://search.lycos.com/main/default.asp?lpv=1&loc=searchhp&query=USA");
    HttpURLConnection tc = (HttpURLConnection) hostURL.openConnection();
    FileOutputStream fs = new FileOutputStream("results.html");
    tc.setDoInput(true);
    tc.connect();
    String inputLine;
    BufferedReader in = new BufferedReader( new InputStreamReader (tc.getInputStream()));
    while(( inputLine = in.readLine()) != null )
    fs.write( inputLine.getBytes());
    fs.close();
    in.close();
    tc.disconnect();
    }catch(Exception e) { System.err.println(e); }
    HTML retrieved by this code is saved in a file "abcde.html"
    but this code copies whole HTML of the above page in a one line.... i was wondering is there
    any way to setWordWrap ( like insert newline char) so "abcde.html" is more readable

  • Exchange command shell output and word wrapping

    everytime our admin runs an exchange management shell command using the >results.txt command so he can send us the results  as a text file, the output often cuts of the end of the text. I have never used the command shell myself so not sure if
    it outputs the same in the shell itself. for example we had a command that should list which roles were running on which server, yet in the results row you get "mailbox, ..." and you cant actually see what other roles are running. Is there a better
    format to output the results as as opposed to text, or anything in the command itself to wrap the text so you can read it all.

    Hello,
    Come back and mark the replies as answers if they help and unmark them if they provide no help.
    I'm marking the reply as answer as there has been no update for a couple of days.
    If you come back to find it doesn't work for you, please reply to us and unmark the answer.
    Cara Chen
    TechNet Community Support

  • Safari and word wrapping in Yahoo Groups

    I have just discovered that the reason why all my Yahoo Group posts are horribly formatted is because I am using Safari. As soon as I use Internet Explorer it works fine. Is this a known problem, and is there anything I can do about it.

    Hi
    This is an on-going Yahoo problem. Same formatting problem occurs in Firefox. As you discovered, the best remedy is Internet Explorer.
    You may want to contact Yahoo via their customer support link. However, given Yahoo's anti-mac/safari position over the past xxx years, I would not expect a reasonable answer.

  • Using excel and word

    How can i view and and print word and excel docs? Do i have to purchase office? Thanks

    Hi Lawrence,
    In addition to the suggestions already offered you may also want to look at the following (free) applications which are compatible with MS Office:
    1. NeoOffice - http://www.neooffice.org/
    2. AbiWord - http://www.abisource.com/

Maybe you are looking for