Using jtextpane as jlist cell renderer component

hi,
I want to use Jlist (in a Jscrollpane) to list a series of boxes of text. The boxes have to be kept the same width, but the height can vary depending on the amount of text.
I want to use jtextpane because it wraps automatically on word boundaries... although I am confused by the jtextpane functionality...
but I just can't seem to crack it: presumably its going to involve
class MyCellRenderer extends JTextPane implements CellRenderer {
public Component getListCellRendererComponent( ...
then what ??? help!
mike rodent
PS also, how to make Jlist put a line (a single line) between each of the components in its list... it's no good doing setBorder inside the above method, as you then get 2 lines coalescing between adjacent Jlist elements...

PS also, how to make Jlist put a line (a single line) between each of
the components in its list... it's no good doing setBorder inside the
above method, as you then get 2 lines coalescing between adjacent
Jlist elements...Who says you need to have a Border with top and bottom lines?

Similar Messages

  • Customizing JList Cell Renderer

    Hi all,
    I got a problem with JList not rendering properly in my program. basically I create a customized renderer by extending JPanel and implementing ListCellRenderer.
    but somehow i cannot get the tooltiptext from the JLabel inside my JPanel (the renderer) to display the tooltiptext and responding to my mouse gesture. here's a snippet of my code.
    did i do something wrong?
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class TestR {
         private static class ListItem {
              private Color color;
              private String value;
              public ListItem(Color c, String s) {
                   color = c;
                   value = s;
              public Color getColor() {
                   return color;
              public String getValue() {
                   return value;
         private static class MyCellRenderer extends JPanel implements
                   ListCellRenderer {
              private JLabel lbl;
              public MyCellRenderer() {
                   // Don't paint behind the component
                   setOpaque(true);
                   setLayout(new BorderLayout());
                   lbl = new JLabel();
                   add(lbl);
              // Set the attributes of the
              //class and return a reference
              public Component getListCellRendererComponent(JList list, Object value, // value to display
                        int index, // cell index
                        boolean iss, // is selected
                        boolean chf) // cell has focus?
                   // Set the text and
                   //background color for rendering
                   lbl.setText(((ListItem) value).getValue());
                   lbl.setToolTipText("tooltip: "+((ListItem) value).getValue());
                   setBackground(((ListItem) value).getColor());
                   // Set a border if the
                   //list item is selected
                   if (iss) {
                        setBorder(BorderFactory.createLineBorder(Color.blue, 2));
                   } else {
                        setBorder(BorderFactory.createLineBorder(list.getBackground(),
                                  2));
                   return this;
         // Create a window
         public static void main(String args[]) {
              JFrame frame = new JFrame("Custom List Demo");
              frame.addWindowListener(new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              // Use a list model that
              //allows for updates
              DefaultListModel model = new DefaultListModel();
              JList statusList = new JList(model);
              statusList.setCellRenderer(new MyCellRenderer());
              // Create some dummy list items.
              ListItem li = new ListItem(Color.cyan, "test line one");
              model.addElement(li);
              li = new ListItem(Color.yellow, "foo foo foo");
              model.addElement(li);
              li = new ListItem(Color.green, "quick brown fox");
              model.addElement(li);
              // Display the list   
              JPanel panel = new JPanel();
              panel.add(statusList);
              frame.getContentPane().add("Center", panel);
              frame.pack();
              frame.setVisible(true);
    }

    hi!
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class TestR {
         private static class ListItem {
              private Color color;
              private String value;
              public ListItem(Color c, String s) {
                   color = c;
                   value = s;
              public Color getColor() {
                   return color;
              public String getValue() {
                   return value;
         private static class MyCellRenderer extends JPanel implements
                   ListCellRenderer {
              private JLabel lbl;
              public MyCellRenderer() {
                   // Don't paint behind the component
                   setOpaque(true);
                   setLayout(new BorderLayout());
                   lbl = new JLabel();
                   add(lbl);
              // Set the attributes of the
              //class and return a reference
              public Component getListCellRendererComponent(JList list, Object value, // value to display
                        int index, // cell index
                        boolean iss, // is selected
                        boolean chf) // cell has focus?
                   // Set the text and
                   //background color for rendering
                   lbl.setText(((ListItem) value).getValue());
                   /*lbl.*/setToolTipText("tooltip: "+((ListItem) value).getValue());
                   setBackground(((ListItem) value).getColor());
                   // Set a border if the
                   //list item is selected
                   if (iss) {
                        setBorder(BorderFactory.createLineBorder(Color.blue, 2));
                   } else {
                        setBorder(BorderFactory.createLineBorder(list.getBackground(),
                                  2));
                   return this;
         // Create a window
         public static void main(String args[]) {
              JFrame frame = new JFrame("Custom List Demo");
              frame.addWindowListener(new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              // Use a list model that
              //allows for updates
              DefaultListModel model = new DefaultListModel();
              JList statusList = new JList(model);
              statusList.setCellRenderer(new MyCellRenderer());
              // Create some dummy list items.
              ListItem li = new ListItem(Color.cyan, "test line one");
              model.addElement(li);
              li = new ListItem(Color.yellow, "foo foo foo");
              model.addElement(li);
              li = new ListItem(Color.green, "quick brown fox");
              model.addElement(li);
              // Display the list   
              JPanel panel = new JPanel();
              panel.add(statusList);
              frame.getContentPane().add("Center", panel);
              frame.pack();
              frame.setVisible(true);
    }try this out. this may help you. note at line no 50. /*lbl.*/setToolTipText("tooltip: "+((ListItem) value).getValue());:)
    Aniruddha

  • Changing JList cell renderer on selection

    Hi,
    In our application we need to change the renderer of the selected cell of JList to JTextArea while maintaining default cell renderer for unselected cells. I tried by providing custom cell renderer (code is given below) but it does not work..:-(. Though the component used by JList for rendering the cell is JTextArea, the height of the cell remains same as that of unselected cells. Our requirement is to change the cell height of the selected row so as to give a feel that selected row expands and shows some more information about the selected item to the user.
    Here is the code snippet of the cell renderer that I wrote:
    class CellRenderer1 extends DefaultListCellRenderer{
    private JTextArea selTxtArea;
    CellRenderer1() {
    selTxtArea = new JTextArea(3,20);
    this.setOpaque(true);
    public Component getListCellRendererComponent(JList list,
    Object value, int index,
    boolean isSelected, boolean cellHasFocus) {
    String name = (String) value;
    if ( isSelected ) {
    selTxtArea.setBackground(list.getSelectionBackground());
    selTxtArea.setForeground(list.getSelectionForeground());
    selTxtArea.setText(name + "\n" + name);
    return selTxtArea;
    else {
    this.setBackground(list.getBackground());
    this.setForeground(list.getForeground());
    this.setText(name);
    return this;
    //return this;
    Any pointers or help will be highly appreciated.
    Thanks
    Atul

    JList calculates fixedCellHeight and then uses the same for every cell. This was causing the problem. By overriding the getRowHeight method of BasicListUI class I was able to achieve different cell heights for selected and unselected rows. Following is the code snippet which shows how this was achieved:
    protected int getRowHeight(int row) {
    if ( (cellHeights == null) || (cellHeights.length < row )) {
    cellHeights = new int[row];
    ListModel model = list.getModel();
    Object value = model.getElementAt(row);
    ListSelectionModel selModel = list.getSelectionModel();
    boolean isSelected = selModel.isSelectedIndex(row);
    Component comp = list.getCellRenderer().
    getListCellRendererComponent( list, value, row,
    isSelected, false);
    Dimension dim = comp.getPreferredSize();
    int height = dim.height;
    cellHeights[row] = height;
    return cellHeights[row];
    }

  • Custom JList Cell renderer

    Hey guys, i've made a JList put it inside a JScrollPane.
    All working nicely.
    I'm making my own cell renderer, which extends JLabel and implements ListCellRenderer, just the usual
    inside the getList...Component() method, im just adding in a new Icon and adding a border
    And setting the text via the setText method, also using a bit of html to format the text so it sits there nicely.
    It's exactly how i want it, however there's this issue, when i populate alot of items for some reason the JScrollPane isnt like aware of more items and scroll bar isnt made, but u can tell theres more because its cut off at the end.
    Also, when i resize it so the JScrollPanes width is really small, each JList items text is wrapped and causing some of the text to be hidden.
    I want to know how to fix these issues with no horizontal scroll bar etc
    what exactly is the issue?
    Is it because of the custom renderer?
    Thanks for your help guys.

    Is it because of the custom renderer?You tell us!
    Somewhere in your code you have the line:
    list.setCellRenderer(...);
    If you comment out that line does it work correctly? If so then the problem is the renderer and we can't help you solve the problem since we don't know what your code looks like.
    If you need furthre help then you need to post a [url http://www.physci.org/codes/sscce.jsp]Simple Executable Demo Program that shows the problem

  • Using JScrollpane via Custom Cell Renderer.Please Help

    Chaps,
    I have a question regarding scrolling of a JList.
    I have written a class (FTRDList) that has an Custom Cell Renderer.
    I want the list to be scrollable.
    This class is being called by many other classes.
    Now,as the FTRDList class is being called by many classes,i need
    to have all these classes to have the flwg statement
    add(new JScrollPane(FTRDList)),BorderLayout.CENTER);
    This can be a lot of work to chaneg all classes
    Rather,is it possible to have the JScrollPane built in the
    FTRDList class once and for all and let all classes call
    it by
    add(FTRDList,BorderLayout.CENTER);
    Please can anyone tell me how to make the FTRDList class Scrollable?
    Or is this not possible at all?
    Attached is the class:
    public class FTRDList extends JList {
        /* Inner class for Custom Cell Renderer */
        class MyCellRenderer extends JLabel implements ListCellRenderer {
        public Component getListCellRendererComponent(JList list,
                                                      Object value,            // value to display
                                                      int index,               // cell index
                                                      boolean isSelected,      // is the cell selected
                                                      boolean cellHasFocus) {  // the list and the cell have the focus
                setText(value.toString());
                if (isSelected) {
                setBackground(isSelected ? Color.red : Color.yellow);
             setForeground(isSelected ? Color.white : Color.black);
                setEnabled(list.isEnabled());
                setOpaque(isSelected);
                return this;
        public FTRDList() {
            super();
            setSelectedIndex(0);
            /** Invoke the cell Renderer */
            setCellRenderer(new MyCellRenderer());
            setOpaque(false);    

    I HAVE ALSO POSTED THIS IN THE JAVA PROGRAMMING FORUM PLEASE DONT GET OFFENDED AS I AM EXPECTING AN URGENT RESPONSEWell, someone has probably already answered this question in the Java forum, so I won't waste my time and answer it again here.

  • JTree as cell renderer for JList

    I have an application that requires to display a list of tree-structured data.
    So I've used JTree a the cell renderer for the JList, and I can see a list of trees with that data in.
    However, the Jtree doesn't respond to Mouse messages, even if I dispatch the to it manually. So the tree is essentially dead.
    Does anybody know how to fix this?

    I'm not sure if they have the same thing for lists though.Yes, it is so - a cellrenderer or celleditor is a component, that is only there during it is used - a cellrenderer is there as long as it needs to paint the contents, a celleditor is there, if an edit-process is invoked and it will get messages as long as the editing process continues - after finishing editing, the component is no longer there - normally the renderer is called after that, to render the new contents into the rectangle of that cell, because the contents in its non-editing state may look other than that from the editor during the editing-state.
    greetings Marsian

  • Custom Cell Renderer for JList

    I'm getting some strange behaviour from my custom cell renderer.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class TestRenderer implements ListCellRenderer {
      private JPanel jpCell = new JPanel();
      public Component getListCellRendererComponent
          (JList list, Object value, int index, boolean isSelected,
           boolean cellHasFocus) {
        jpCell.add(new JLabel("Render"));
        return jpCell;
    import javax.swing.*;
    import java.awt.*;
    public class TestPanel extends JFrame {
         public TestPanel() {
              JList jlst = new JList(new String[]{"Value", "Value2", "Value3"});
              jlst.setCellRenderer(new TestRenderer());
              JPanel panel = new JPanel();
              panel.add(jlst);
              add(panel);
         public static void main(String[] args) {
              TestPanel frame = new TestPanel();
              frame.setSize(300, 300);
              frame.setLocationRelativeTo(null);
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.setVisible(true);
    }As you will see the renderer displays the string several times in each cell depending on which layout manager I use. However, if I replace the JPanel with a JLabel and set the String as text on the label the String is only printed once per cell. I can't see to find the reason for this.
    Edited by: 811488 on 18-Nov-2010 09:44
    Edited by: 811488 on 18-Nov-2010 09:45
    Edited by: 811488 on 18-Nov-2010 09:45

    So getListCellRendererComponent returns a component whose paintComponent method is called with the Graphics object of the JList Yes, except that the paint(...) method is called. There is a difference. paintComponent() only paints the component. In the case of a JPanel you would get a boring gray colored component. paint() will paint the component and its children and the Border of the component as well. So you get a much more exiting component.
    Read the section from the Swng tutorial on [url http://download.oracle.com/javase/tutorial/uiswing/painting/index.html]Custom Painting for more information.
    So the state of the cell is not the state of the cell Renderer Component meaning the image rendered onto the cell only reflects the state of the Cell Renderer Component at the time the cell was rendered.Yes which is why this method should be efficient because repainting is consistently being done for all the cells. For example every time row selection changes multiple rows need to be repainted. Think of this same concept when you use a JTable which also contains multiple columns for each row.
    That is why you should not be adding/removing components in the rendering code.
    It makes sense except that if this was the case the first version of the Render that I posted should have been rendered first with one "Render" then two then three, shouldn't it?Yes, except that you can't control when or how often the rendering is done. Add the following to the renderer:
    System.out.println(index + " : " + jpCell.getComponentCount());You will see that rendering is done multiple times. The JList tries to determine its preferred width. To do this it loops through all the items in the list and invokes the renderer to get the width of the largest renderer. Well the largest width is the last renderer because 3 labels have been added to the panel. So that width becomes the preferred width of the list. Then the GUI is displayed and the list is painted. Every time the renderer is called an new label is added, but after the 3rd label there is no room to paint the label so it is truncated.
    Change your code to the following:
    //add(panel);
    add(jlst);Now change the width of the frame to see what happens.
    Given all the help you have received, I expect to see many "helpfull answers" selected as well as a "correct answer" (if you want help in the future that is).

  • JList Cell Height Problem

    I am trying to use a customer cell renderer for a JList. It sort of works, but my cell heights are incorrect because when a cell is selected the JPanel returned from my cell renderer need more space to paint on than an unselected list item.
    Sample code below demontrates the problem - use it as the cell renderer for something and make some selections - you can see that when the text is enlarged when the cell is selected, it is not resized to accommodate the larger text.
    I've tried various combinations of setSize, revalidate etc at various points but nothing helps...
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class TestListCellRenderer extends JPanel implements ListCellRenderer {
         JLabel l;
         public TestListCellRenderer() {
              setLayout( new BorderLayout() );
              l = new JLabel( );
              setBorder( BorderFactory.createLineBorder( Color.BLACK ) );
              add( l, BorderLayout.NORTH );
         public Component getListCellRendererComponent(
                   JList list,
                   Object value,
                   int index,
                   boolean isSelected,
                   boolean hasFocus ) {
              if( isSelected == false ) {
                   l.setText( value.toString() );
                   l.setFont( new Font( "Serif", Font.BOLD, 12 ) );
              else {
                   l.setText( value.toString() );
                   l.setFont( new Font( "Serif", Font.BOLD, 18 ) );
              return this;
    }

    I came across this thread when I was having a similar problem. I have found a way to get it to work.
    My problem was this: I have a list of news headlines. When I increased the font size of the items in my list I needed to increase the height of each cell in the list so that the headline wouldn't get cut off top and bottom by the restrictive height of the list cell.
    Solution is to use setFixedCellHeight(int height) from the JList class.
    In my case I find set the fixed cell height in 3 places.
    the constructor - when the list is being created
    the cell renderer method - when the list is being rendered
    in an action listener method - to act when a user changes the size of the font.
    The code excerpt below is a chopped down version of the working code but gives you an idea.
    public class NewsWindow implements ListSelectionListener {
         /** Component which holds the headlines */
         public JList list;
         public NewsWindow(Container parent, WindowProperties properties) {
              DefaultListModel listModel = new DefaultListModel();
              list = new JList(listModel);
              list.setCellRenderer(new HeadlineCellRenderer());
              bounceListCellHeight(); // set the correct list cell height up front
         /** when the font size has changed this method is eventually called via a super class */
         public void fontSizeHasChangedListener() {         
         bounceListCellHeight();
         /** THIS METHOD SETS THE HEIGHT OF THE LIST CELLS */     
         public void bounceListCellHeight() {
              int height = getFontMetrics(getNewsFont()).getHeight(); // get the height of the font
              list.setFixedCellHeight(height + 10); // set the cell height
         * Inner class to render the list.
         private class HeadlineCellRenderer extends JLabel implements ListCellRenderer {
              public HeadlineCellRenderer() {
              setOpaque(true);
              public Component getListCellRendererComponent(JList myList, Object value, int index, boolean isSelected, boolean cellHasFocus) {
              bounceListCellHeight(); // call the method to set the list cell height
              setText(getHeadlineText());
              this.revalidate();
              setFont(getNewsFont());
              return this;
    Hope this is of some help.

  • Problem with addRow and MultiLine Cell renderer

    Hi ,
    Ive a problem with no solution to me .......
    Ive seen in the forum and Ivent found an answer.......
    The problem is this:
    Ive a JTable with a custom model and I use a custom multiline cell renderer.
    (becuse in the real application "way" hasnt static lenght)
    When I add the first row all seem to be ok.....
    when I try to add more row I obtain :
    java.lang.ArrayIndexOutOfBoundsException: 1
    at javax.swing.SizeSequence.insertEntries(SizeSequence.java:332)
    at javax.swing.JTable.tableRowsInserted(JTable.java:2926)
    at javax.swing.JTable.tableChanged(JTable.java:2858)
    at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableMo
    del.java:280)
    at javax.swing.table.AbstractTableModel.fireTableRowsInserted(AbstractTa
    bleModel.java:215)
    at TableDemo$MyTableModel.addRow(TableDemo.java:103)
    at TableDemo$2.actionPerformed(TableDemo.java:256)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
    64)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstra
    ctButton.java:1817)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:419)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:245)
    at java.awt.Component.processMouseEvent(Component.java:5134)
    at java.awt.Component.processEvent(Component.java:4931)
    at java.awt.Container.processEvent(Container.java:1566)
    at java.awt.Component.dispatchEventImpl(Component.java:3639)
    at java.awt.Container.dispatchEventImpl(Container.java:1623)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
    at java.awt.Container.dispatchEventImpl(Container.java:1609)
    at java.awt.Window.dispatchEventImpl(Window.java:1590)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
    read.java:197)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    This seems to be caused by
    table.setRowHeight(row,(getPreferredSize().height+2)); (line 164 of my example code)
    About the model I think its ok.....but who knows :-(......
    Please HELP me in anyway!!!
    Example code :
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class TableDemo extends JFrame {
    private boolean DEBUG = true;
    MyTableModel myModel = new MyTableModel();
    MyTable table = new MyTable(myModel);
    int i=0;
    public TableDemo() {
    super("TableDemo");
    JButton bottone = new JButton("Aggiungi 1 elemento");
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(bottone,BorderLayout.NORTH);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    bottone.addActionListener(Add_Action);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class MyTable extends JTable {
    MultiLineCellRenderer multiRenderer=new MultiLineCellRenderer();
    MyTable(TableModel tm)
    super(tm);
    public TableCellRenderer getCellRenderer(int row,int col) {
              if (col==1) return multiRenderer;
              else return super.getCellRenderer(row,col);
    class MyTableModel extends AbstractTableModel {
    Vector data=new Vector();
    final String[] columnNames = {"Name",
    "Way",
    "DeadLine (ms)"
    public int getColumnCount() { return 3; }
    public int getRowCount() { return data.size(); }
    public Object getValueAt(int row, int col) {
    Vector rowdata=(Vector)data.get(row);
                                                                return rowdata.get(col); }
    public String getColumnName(int col) {
    return columnNames[col];
    public void setValueAt (Object value, int row,int col)
         //setto i dati della modifica
    Vector actrow=(Vector)data.get(row);
    actrow.set(col,value);
         this.fireTableCellUpdated(row,col);
         public Class getColumnClass(int c)
              return this.getValueAt(0,c).getClass();
         public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col == 1)
    return false;
    else
    return true;
    public void addRow (String name,ArrayList path,Double dead) {
         Vector row =new Vector();
         row.add(name);
         row.add(path);
         row.add(dead);
         row.add(name); //!!!Mi tengo questo dato da utilizzare come key per andare a
         //prendere il path nella lista dei paths di Project
         //(needed as key to retrive data if name in col. 1 is changed)
         data.add(row);
         //Inspector.inspect(this);
         System.out.println ("Before firing Adding row...."+this.getRowCount());
         this.fireTableRowsInserted(this.getRowCount(),this.getRowCount());
    public void delRow (String namekey)
    for (int i=0;i<this.getRowCount();i++)
    if (namekey.equals(this.getValueAt(i,3)))
    data.remove(i);
    this.fireTableRowsDeleted(i,i);
    //per uscire dal ciclo
    i=this.getRowCount();
    public void delAllRows()
    int i;
    int bound =this.getRowCount();     
    for (i=0;i<bound;i++)     
         {data.remove(0);
         System.out.println ("Deleting .."+data);
    this.fireTableRowsDeleted(0,i);          
    class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
    private Hashtable rowHeights=new Hashtable();
    public MultiLineCellRenderer() {
    setEditable(false);
    setLineWrap(true);
    setWrapStyleWord(true);
    //this.setBorder(new Border(
    public Component getTableCellRendererComponent(JTable table,Object value,                              boolean isSelected, boolean hasFocus, int row, int column) {
    //System.out.println ("Renderer called"+value.getClass());
    if (value instanceof ArrayList) {
    String way=new String     (value.toString());
    setText(way);
    TableColumn thiscol=table.getColumn("Way");
    //System.out.println ("thiscol :"+thiscol.getPreferredWidth());
    //setto il size della JTextarea sulle dimensioni della colonna
    //per quanto riguarda il widht e su quelle ottenute da screen per l'height
    this.setSize(thiscol.getPreferredWidth(),this.getPreferredSize().height);
    // set the table's row height, if necessary
    //System.out.println ("Valore getPreferred.height"+getPreferredSize().height);
         if (table.getRowHeight(row)!=(this.getPreferredSize().height+2))
         {System.out.println ("Setting Row :"+row);
             System.out.println ("Dimension"+(getPreferredSize().height+2));
             System.out.println ("There are "+table.getRowCount()+"rows in the table ");
             if (row<table.getRowCount())
             table.setRowHeight(row,(getPreferredSize().height+2));
    else
    setText("");
    return this;
    /**Custom JTextField Subclass che permette all'utente di immettere solo numeri
    class WholeNumberField extends JTextField {
    private Toolkit toolkit;
    private NumberFormat integerFormatter;
    public WholeNumberField(int value, int columns) {
    super(columns);
    toolkit = Toolkit.getDefaultToolkit();
    integerFormatter = NumberFormat.getNumberInstance(Locale.US);
    integerFormatter.setParseIntegerOnly(true);
    setValue(value);
    public int getValue() {
    int retVal = 0;
    try {
    retVal = integerFormatter.parse(getText()).intValue();
    } catch (ParseException e) {
    // This should never happen because insertString allows
    // only properly formatted data to get in the field.
    toolkit.beep();
    return retVal;
    public void setValue(int value) {
    setText(integerFormatter.format(value));
    protected Document createDefaultModel() {
    return new WholeNumberDocument();
    protected class WholeNumberDocument extends PlainDocument {
    public void insertString(int offs,
    String str,
    AttributeSet a)
    throws BadLocationException {
    char[] source = str.toCharArray();
    char[] result = new char[source.length];
    int j = 0;
    for (int i = 0; i < result.length; i++) {
    if (Character.isDigit(source))
    result[j++] = source[i];
    else {
    toolkit.beep();
    System.err.println("insertString: " + source[i]);
    super.insertString(offs, new String(result, 0, j), a);
    ActionListener Add_Action = new ActionListener() {
              public void actionPerformed (ActionEvent e)
              System.out.println ("Adding");
              ArrayList way =new ArrayList();
              way.add(new String("Uno"));
              way.add(new String("Due"));
              way.add(new String("Tre"));
              way.add(new String("Quattro"));
              myModel.addRow(new String("Nome"+i++),way,new Double(0));     
    public static void main(String[] args) {
    TableDemo frame = new TableDemo();
    frame.pack();
    frame.setVisible(true);

    In the addRow method, change the line
    this.fireTableRowsInserted(this.getRowCount(),this.getRowCount()); to
    this.fireTableRowsInserted(data.size() - 1, data.size() - 1);Sai Pullabhotla

  • JTable with JButton Cell renderer

    How can I get buttons (JButtons) to "depress" properly in a JTable when using them as the cell renderer for a specific column in a JTable? Currently when pressing any button in the column, there is no change in the visible state of the button, i.e. it doesn't change color to create impression of depression.

    Is the [problem not the fact that the JTable cell renderers merely rubberstamp each cell with the appropriate display, i.e. the actual component in the cell is not an actual button (just looks like one)? If this is the case, then the same problem will persis with a JToggleButton as well won't it?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Jlist as a Cell Renderer

    Hi ,
    I would reaally appreciate if someone could post an example of using a JList as a custom Cell renderer
    Thank you.

    Here's a start (I couldn't be bothered to set an editor too):import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class Test extends JFrame {
        public Test () {
            JTable table = new JTable (new TestTableModel ());
            table.setDefaultRenderer (Integer[].class, new TestTableCellRenderer ());
            table.setRowHeight (50);
            getContentPane ().setLayout (new BorderLayout ());
            getContentPane ().add (new JScrollPane (table));
            setDefaultCloseOperation (DISPOSE_ON_CLOSE);
            setTitle ("Test");
            pack ();
            setLocationRelativeTo (null);
            setVisible (true);
        public static void main (String[] parameters) {
            new Test ();
        private class TestTableModel implements TableModel {
            private final static int N = 10;
            private Object[][] data;
            private ColumnData[] columnData;
            public TestTableModel () {
                data = new Object[N][2];
                for (int i = 0; i < N; i ++) {
                    data[0] = new Integer (i);
    data[i][1] = new Integer[i + 1];
    for (int j = 0; j <= i; j ++) {
    ((Integer[]) data[i][1])[j] = new Integer (j);
    columnData = new ColumnData[] {
    new ColumnData ("n", Integer.class),
    new ColumnData ("0..n", Integer[].class)
    public int getColumnCount () {
    return columnData.length;
    public int getRowCount () {
    return data.length;
    public boolean isCellEditable (int row, int column) {
    return false;
    public void setValueAt (Object value, int row, int column) {}
    public Class getColumnClass (int column) {
    return columnData[column].classType;
    public Object getValueAt (int row, int column) {
    return data[row][column];
    public String getColumnName (int column) {
    return columnData[column].name;
    public void addTableModelListener (TableModelListener listener) {}
    public void removeTableModelListener(TableModelListener listener) {}
    private class ColumnData {
    public String name;
    public Class classType;
    public ColumnData (String name, Class classType) {
    this.name = name;
    this.classType = classType;
    private class TestTableCellRenderer extends JScrollPane implements TableCellRenderer {
    private JList list;
    public TestTableCellRenderer () {
    list = new JList ();
    setViewportView (list);
    public Component getTableCellRendererComponent (JTable table, Object value, boolean selected, boolean focused, int row, int column) {
    list.setListData ((Integer[]) value);
    return this;
    Kind regards,
      Levi

  • Help: Jbo Exception non blocking when using table cell renderer?

    Hi,
    JClient 9.5.2.
    When using Table Cell Renderer on an table cell attribute that is defined mandatory and activating the insert button, the (oracle.jbo.AttrValException) JBO-27014 exception is caught but it is not blocking and a new row is still inserted.
    The JClient component demo, table attribute list, has the same behaviour.
    You can add multiple rows even if not all required attributes have been documented.
    Can a Swing specialist help me on this one?
    Example of Table Cell Renderer:
    public class TableBasicStatusRenderer extends DefaultTableCellRenderer
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
    int row, int column)
    JLabel lb = new JLabel((String) StaticData.getStatusName(value)); // retrieves label from Map
    return lb;
    Regards
    Frederic

    Hi,
    I found something interesting, it could be a WORKAROUND!
    I noticed that in another detail panel with table layout the JBO exception was blocking and adding another row before completing the row was NOT possible.
    In the create method of the entity object of the displayed View Object I iterate over the detail row iterator to retrieve a maximum value.
    By the end of the method the pointer is positionned after the last row.
    So I added to the detail panel that doesn't block following code:
    In create method of detail Entity Object Impl (only one entity object involved for this View)
    // Retrieve master EntityObjectImpl from association:
    PostalTariffImpl postalTariffImpl = getPostalTariffAssoc();
    // Retrieve detail default row iterator
    RowIterator ri = postalTariffImpl.getPostalDetailGroupAssoc();
    // Position pointer after last row
    ri.last();
    ri.next();
    Question: Why does this solve the problem?
    Regards
    Frederic
    PS Les mysteres de l'informatique!

  • How to get JList cells to use available space

    Hello all!
    I have a Swing problem for which I could not find any hints in Swing books or the web.
    There is a JList with a custom cell renderer. I'd like to make the cells take all the available space so the JList's area is completely filled with the cells.
    This doesn't work, unfortunately. When I resize the frame containing the JList, the cells only get resized horizontally. Their height remains the same so below all cells there is just the JList background.
    I did not call JList.setFixedCellHeight or so. Btw, when I put a single custom cell component in a JPanel, it resizes perfectly.
    Thanks in advance for any hints!

    I did not call JList.setFixedCellHeightWhy not?import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import javax.swing.*;
    public class ListCellSpace {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new ListCellSpace().makeUI();
        public void makeUI() {
            Object[] data = {"One", "Two", "Three", "Four", "Five", "Six"};
            final JList list = new JList(data);
            list.addComponentListener(new ComponentAdapter() {
                @Override
                public void componentResized(ComponentEvent e) {
                    list.setFixedCellHeight(list.getHeight()/list.getModel().getSize());
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(200, 200);
            frame.setLocationRelativeTo(null);
            frame.add(list);
            frame.setVisible(true);
    }You do realize that if the JList is sized too small, the item text will be vertically truncated, don't you?
    db

  • Custom table model, table sorter, and cell renderer to use hidden columns

    Hello,
    I'm having a hard time figuring out the best way to go about this. I currently have a JTable with an custom table model to make the cells immutable. Furthermore, I have a "hidden" column in the table model so that I can access the items selected from a database by their recid, and then another hidden column that keeps track of the appropriate color for a custom cell renderer.
    Subject -- Sender -- Date hidden rec id color
    Hello Pete Jan 15, 2003 2900 blue
    Basically, when a row is selected, it grabs the record id from the hidden column. This essentially allows me to have a data[][] object independent of the one that is used to display the JTable. Instinctively, this does not seem right, but I don't know how else to do it. I know that the DefaultTableModel uses a Vector even when it's constructed with an array and I've read elsewhere that it's not a good idea to do what I'm trying to do.
    The other complication is that I have a table sorter as well. So, when it sorts the objects in the table, I have it recreate the data array and then set the data array of the ImmutableTableModel when it has rearranged all of the items in the array.
    On top of this, I have a custom cell renderer as well. This checks yet another hidden field and displays the row accordingly. So, not only does the table sort need to inform the table model of a change in the data structure, but also the cell renderer.
    Is there a better way to keep the data in sync between all of these?

    To the OP, having hidden columns is just fine, I do that all the time.. Nothing says you have to display ALL the info you have..
    Now, the column appears to be sorting properly
    whenever a new row is added. However, when I attempt
    to remove the selected row, it now removes a seemingly
    random row and I am left with an unselectable blank
    line in my JTable.I have a class that uses an int[] to index the data.. The table model displays rows in order of the index, not the actual order of the data (in my case a Vector of Object[]'s).. Saves a lotta work when sorting..
    If you're using a similar indexing scheme: If you're deleting a row, you have to delete the data in the vector at the INDEX table.getSelectedRow(), not the actual data contained at
    vector.elementAt(table.getSelectedRow()). This would account for a seemingly 'random' row getting deleted, instead of the row you intend.
    Because the row is unselectable, it sounds like you have a null in your model where you should have a row of data.. When you do
    vector.removeElementAt(int), the Vector class packs itself. An array does not. If you have an array, when you delete the row you must make sure you dont have that gap.. Make a new array of
    (old array length-1), populate it, and give it back to your model.. Using Vectors makes this automatic.
    Also, you must make sure your model knows the data changed:
    model.fireTableDataChanged(); otherwise it has no idea anything happened..
    IDK if that's how you're doing it, but it sounds remarkably similar to what I went thru when I put all this together..

  • JList or JTree Cell Renderer

    hi. im doing a scheduler application
    wherein a list is displayed and when user post
    a scheduled activity, a textbox will be painted
    on top of the list, so that you could do away with
    overlapping schedules(2 or more schedule with
    the same time interval/s). Much like as that of
    the MS Outlook calendar.
    Can anyone post a snippet of the code of the
    cell renderer? im having a hard time studying
    cell rendering.
    thank you very much.

    Pls i badly nedd your help. somebody knowledgable on this?

Maybe you are looking for

  • BPM finishes when reaching exception in loop block

    Hi everybody, we got a loop block in BMP. In the loop block we catch mapping errors by using an exception branch. What we can see is that when an exception is thrown the process steps into the exception branch an than is leaving the loop block!! So t

  • Regarding dropdowns in Adobe forms

    Hi experts. I am trying to create an Adobe Form. I have 2 dropdown lists in there. Depending on the value selected in the 1st dropdown i want to populate data in 2nd dropdown list. Can i do this using javascript..If yes , how. Or is there any other a

  • Button in PDF doesn't work

    Hi, I have create a button which I would like to display in my PDF. Below you will see the settings I've used: The problem I'm having is that the button doesn't work. Nothing happens when I open my PDF and click on it. Upon exporting I have select to

  • Linking 2 PDFs in the same web page

    I'm trying to find the coding to link 2 or more PDFs into one embeded Adobe Reader in a web page.  Click one and it loads in the embed reader below.  Click the other and it loads that one instead.  I'm sure it exists somewhere, but I haven't had any

  • Websheet functionality in normal apex application

    Hellow, I was wondering if it was possible to get some functionalities of the websheet aplications to a normal APEX application. What i need is: - The possibilitie to copy pase .xls data into a datagrid - Have an existing dynamic report using that da