Cell Renderer problem JRE1.4

Hi,
I have a JTable cell that uses a JTextArea as renderer. If the cell value is greater than a specific length it wraps and also increases the cell height
If the browser uses JRE1.3 the wrapped text appears right but if the browser uses JRE1.4 it does not display the text in the second line and also the height of the row is not increased.
Can anyone help me with this.
Thanks.

I fixed the problem. My bad. I should have got the column width and set it to the TextArea before trying to get the TextArea height.

Similar Messages

  • Cell Renderer Problem

    Hello. I have a problem with my cell rendering. I am trying to make font in a certain row appear red. My code works well but when you try filtering using row sorter or using the table header's, the colored rows do not change. How can I make the the renderer maybe check for values on every sort?
    Here is a sample of sorting using the table header.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class table extends JFrame {
         public static void main(String[] args) {
              new table();
         public table() {
              initComponents();
              table1.setAutoCreateRowSorter(true);
              for (int i = 0; i<table1.getColumnCount(); i++) {
                   TableColumn column = table1.getColumnModel().getColumn(i);
                   column.setCellRenderer(new myTable());
                   if (i == 0||i==7||i==8){
                        column.setPreferredWidth(100);
                   else if(i==3||i==4){
                        column.setPreferredWidth(180);
                   else if (i==5||i==6){
                        column.setPreferredWidth(120);
                   else if (i==9){
                        column.setPreferredWidth(60);
                   else {
                        column.setPreferredWidth(130);
         public class myTable extends DefaultTableCellRenderer{
              @Override
              public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected,boolean hasFocus, int row, int col){
                   Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                   String qtyValue =  table.getModel().getValueAt(row, 1).toString();
                   if(Integer.valueOf(qtyValue)<3){
                        comp.setForeground(Color.red);
                   else{
                        comp.setForeground(Color.black);
                   return comp;
         private void initComponents() {
              // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
              scrollPane1 = new JScrollPane();
              table1 = new JTable();
              //======== this ========
              Container contentPane = getContentPane();
              contentPane.setLayout(null);
              //======== scrollPane1 ========
                   //---- table1 ----
                   table1.setModel(new DefaultTableModel(
                        new Object[][] {
                             {"Item A", "1"},
                             {"Item B", "2"},
                             {"Item C", "1"},
                             {"Item D", "4"},
                             {"Item E", "5"},
                             {"Item F", "2"},
                             {"Item G", "3"},
                             {"Item H", "7"},
                             {"Item I", "2"},
                             {"Item J", "9"},
                        new String[] {
                             null, null
                   scrollPane1.setViewportView(table1);
              contentPane.add(scrollPane1);
              scrollPane1.setBounds(5, 0, 465, 320);
              { // compute preferred size
                   Dimension preferredSize = new Dimension();
                   for(int i = 0; i < contentPane.getComponentCount(); i++) {
                        Rectangle bounds = contentPane.getComponent(i).getBounds();
                        preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                        preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
                   Insets insets = contentPane.getInsets();
                   preferredSize.width += insets.right;
                   preferredSize.height += insets.bottom;
                   contentPane.setMinimumSize(preferredSize);
                   contentPane.setPreferredSize(preferredSize);
              pack();
              setLocationRelativeTo(getOwner());
              this.setVisible(true);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              // JFormDesigner - End of component initialization  //GEN-END:initComponents
         // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
         private JScrollPane scrollPane1;
         private JTable table1;
         // JFormDesigner - End of variables declaration  //GEN-END:variables
    }

    1. By convention, class names in Java start with an uppercase letter. I would say Table, not table, except that Table is a confusing name for a class.
    2. Swing GUIs should always be constructed and manipulated on the EDT.
    To answer your question
    when you try filtering using row sorter or using the table header's, the colored rows do not change. How can I make the the renderer maybe check for values on every sort?Use the methods of JTable that convert between the view and model index.
    db

  • MultLine Cell Renderer problem

    I have a Custom Cell Renderer which is a scrollPane with a JTextArea. My problem is that the Cell does not scroll when I click the arrows on the vertical scroll Bar.
    Does Anyone Have Any suggestions?
    Here is the code:
    public class ScrollCellRend implements TableCellRenderer {
    private JTextArea ta;
    private JScrollPane scrollPane;
    public ScrollCellRend() {
    ta = new JTextArea();
    scrollPane = new JScrollPane(ta);
    scrollPane.setBorder(BorderFactory.createEmptyBorder());
    ta.setLineWrap(true);
    ta.setWrapStyleWord(true);
    ta.setOpaque(true);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
    ta.setForeground(table.getSelectionForeground());
    ta.setBackground(table.getSelectionBackground());
    } else {
    ta.setForeground(table.getForeground());
    ta.setBackground(table.getBackground());
    ta.setFont(table.getFont());
    if (hasFocus) {
    if (isSelected)
    ta.setBorder(BorderFactory.createLineBorder(Color.blue));
    if (table.isCellEditable(row, column)) {
    ta.setForeground(UIManager.getColor("Table.focusCellForeground"));
    ta.setBackground(UIManager.getColor("Table.focusCellBackground"));
    } else {
    ta.setBorder(new EmptyBorder(1, 2, 1, 2));
    ta.setText((value == null) ? "" : value.toString());
    return scrollPane;

    Hi dave,
    Your must implement a custom TableCellEditor. I'm giving a small demo that can explain how you can achive this thing (3 classes) ---
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    public class MainFrame extends JFrame {
    private boolean DEBUG = true;
    public MainFrame() {
    super("MainFrame");
    Object[][] data = {    {"Mary"} };
    String[] columnNames = {"First Name"};
    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setDefaultRenderer(String.class,new ScrollCellRend());
    TableColumnModel columnModel = table.getColumnModel();
    TableColumn column = columnModel.getColumn(0);
    column.setCellEditor(new LocationTableCellEditor("First Name"));
    column.setPreferredWidth(150);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public static void main(String[] args) {
    MainFrame frame = new MainFrame();
    frame.pack();
    frame.setVisible(true);
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import javax.swing.border.*;
    public class ScrollCellRend implements TableCellRenderer {
    private JTextArea ta;
    private JScrollPane scrollPane;
    public ScrollCellRend() {
    ta = new JTextArea();
    scrollPane = new JScrollPane(ta);
    scrollPane.setBorder(BorderFactory.createEmptyBorder());
    ta.setLineWrap(true);
    ta.setWrapStyleWord(true);
    ta.setOpaque(true);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
    ta.setForeground(table.getSelectionForeground());
    ta.setBackground(table.getSelectionBackground());
    } else {
    ta.setForeground(table.getForeground());
    ta.setBackground(table.getBackground());
    ta.setFont(table.getFont());
    if (hasFocus) {
    if (isSelected)
    ta.setBorder(BorderFactory.createLineBorder(Color.blue));
    if (table.isCellEditable(row, column)) {
    ta.setForeground(UIManager.getColor("Table.focusCellForeground"));
    ta.setBackground(UIManager.getColor("Table.focusCellBackground"));
    } else {
    ta.setBorder(new EmptyBorder(1, 2, 1, 2));
    ta.setText((value == null) ? "" : value.toString());
    return scrollPane;
    import java.awt.*;
    import java.util.EventObject;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class LocationTableCellEditor implements TableCellRenderer, TableCellEditor {
    private JPanel panel = new JPanel(new GridLayout(1,1,2,1));
    private EventListenerList listenerList = new EventListenerList();
    private ChangeEvent event = new ChangeEvent(this);
         private JTextArea ta;
         private JScrollPane scrollPane;
    public LocationTableCellEditor(String type) {
              ta = new JTextArea();
              scrollPane = new JScrollPane(ta);
              scrollPane.setBorder(BorderFactory.createEmptyBorder());
              ta.setLineWrap(true);
              ta.setWrapStyleWord(true);
              ta.setOpaque(true);
    panel.add(scrollPane);
    panel.setPreferredSize(new Dimension(80,15));
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,int row, int column) {
    String s = (String)value;
    ta.setText(s);
    return panel;
    public Component getTableCellEditorComponent(JTable table,
    Object value, boolean isSelected, int row, int column) {
    return getTableCellRendererComponent(table, value,isSelected, true, row, column);
    public boolean isCellEditable(EventObject anEvent) {
    return true;
    public boolean shouldSelectCell(EventObject anEvent) {
    return true;
    public void cancelCellEditing() {
    public boolean stopCellEditing() {
    fireEditingStopped();
    return true;
    public Object getCellEditorValue() {
    return ta.getText();
    public void addCellEditorListener(CellEditorListener l){
    listenerList.add(CellEditorListener.class, l);
    public void removeCellEditorListener(CellEditorListener l) {
    listenerList.remove(CellEditorListener.class, l);
    protected void fireEditingStopped(){
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingStopped(event);
    protected void fireEditingCanceled() {
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingCanceled(event);
    void p(String s) {System.out.println(s);}
    Hope it will help you.
    -Pratap

  • Table Cell Renderer Problem

    I've created a JTable and filled it with data. I created my own header renderer so that I could have more control over the font of the header. I did the same with the cells of the table. Before I created the cell renderer, the cell and row selection (the highlighting of the selections) worked fine. Once I created and implemented the cell renderer, I can set the font the way I want, but the cell no longer highlights the selected rows. It's selecting the rows (my System.out.println in getTableCellRendererComponent() comes back with data). I'm not sure what I'm doing wrong. Here's some of the code....
    runTable = new JTable(tableModel);
    runTable.setBackground(Color.white);
    runTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    CellRenderer cellRenderer = new CellRenderer();
    // Set column 1's header
    String[] header1 = {"Time"," Of ","Day"};
    TableColumn col1 = runTable.getColumnModel().getColumn(0);
    col1.setHeaderValue(header1);
    col1.setCellRenderer(cellRenderer);
    String[][] parms = zoomplot.zmenubar.getParmSel();
    TableColumn col;
    for (int i = 0; i < parms.length; i++) {
    String[] header = new String[3];
    header[0] = parms[0];
    header[1] = " (" + parms[i][1] + ") ";
    header[2] = "Rate " + parms[i][2];
    col= runTable.getColumnModel().getColumn(i + 1);
    col.setHeaderValue(header);
    // col.setMaxWidth(100);
    col.setCellRenderer(cellRenderer);
    class CellRenderer extends JLabel
    implements TableCellRenderer {
    Color background = null;
    public CellRenderer() {
    // setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    // setOpaque(false);
    public Component getTableCellRendererComponent(
    JTable table, Object value,
    boolean isSelected, boolean hasFocus,
         int row, int col) {
    removeAll();
    invalidate();
    add(Box.createVerticalGlue());
    setText((String)value);
    setFont(Utils.courierBold11);
    setHorizontalAlignment(SwingConstants.CENTER);
    setAlignmentX((float)0.5);
    if (isSelected) {
    this.setBackground(Color.black);
    // System.out.println("Row " + row + ", Col " + col + " is selected");
    return this;
    public void setBackground(Color back) {
    background = back;
    super.setBackground(back);
    I even tried to "manually" set the highlighting in getTableCellRendererComponent() ...
    if (isSelected) {
    this.setBackground(Color.black);
    but that didn't work either. Any Ideas..... Thanks.....

    When creating a custom renderer it is generally easier to extend the DefaultTableCellRenderer as it already has the custom code to do row highlighting, border selection etc. Also it has been optimized to paint faster.
    In your particular case it looks like your don't even need to do that. Just create a DefaultTableCellRenderer and change a few of its properties. Something like:
    // Override default renderer for a specific column
    DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
    centerRenderer.setHorizontalAlignment( JLabel.CENTER );
    centerRenderer.setFont(...);
    table.getColumnModel().getColumn(2).setCellRenderer( centerRenderer );

  • JTable Cell Renderer problems

    Hi,
    I ahve created a cellRenderer so that it renders jCheckBox in the cell. However, the check boxes are intended for use by boolean values, and thats how they work best. However the problem i am having is that i want to render the boxes into cells that have either a 1 or 0. I have managed to do this and display the correct state of the box but when i want to make changes i have to change the value 0 or 1 inorder to change the check box. Is there a way i can select or deselect the checkbox when editing???
    Thanks in advance
    Rudy

    Hi,
    I am going to change my table model to try and make it more generic. However before i do so and mess everything up i would like to know if the following will work.
    1. I will pass to the constructor names of columns that i want to be rendered as checkboxes.
    2. I will then get the column index of that column using
    public int getColumnIndex(String name) {
        for(int i = 0; i < columnNames.length; i++){
          if(columnNames.trim().equals(name)){
    return i;
    return -1; //if fails
    3. In my get columnclass which is implemented as follows (from java demo)
    public Class getColumnClass(int column) {
        int type;
        try {
          type = metaData.getColumnType(column + 1);
        catch (SQLException e) {
          return super.getColumnClass(column);
        switch (type) {
          case Types.CHAR:
          case Types.VARCHAR:
          case Types.LONGVARCHAR:
            return String.class;
          case Types.BIT:
            return Boolean.class;
          case Types.TINYINT:
          case Types.SMALLINT:
          case Types.INTEGER:
            return Integer.class;
          case Types.BIGINT:
            return Long.class;
          case Types.FLOAT:
          case Types.DOUBLE:
            return Double.class;
          case Types.DATE:
          case Types.TIMESTAMP:
            return java.sql.Date.class;
          default:
            return Object.class;
    }I can add a condition that "if column (int) == the indexes if previously retrieved then return boolean class"
    With this work columns that has either Y, N or null or 0, 1, or null???
    I may change the columnNames to a vector so that i can use the contains method and therefore not need to find the index.
    Will this work???
    Thanks
    Rudy

  • JTable Cell RENDERER PROBLEM!!! PLEASE HELP

    I have been trying to code stuff with Java TableCellRenderer...here is my current code:
    private class DetailTableCellRenderer extends DefaultTableCellRenderer{
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    if(row==0 && column==0)
    this.setBackground(Color.red);
    this.setHorizontalAlignment(CENTER);
    this.setHorizontalTextPosition(CENTER);
    return this;
    and in jbinit(), i have this line:
    DetailedTable.setDefaultRenderer(String.class,new
    DetailTableCellRenderer());
    *By the way, ive tried putting Color.class, JTable.class, JLabel.class, and just about everything else imaginible...nothing seems to work...
    my point is to center the text in a JTable and to customize the background color of certain cells...
    I have tried looking for this topic multiple times, but every time a piece of code is given, the code doesnt work...please offer suggestions...any are much appreciated...
    thanks,
    Sid

    I just scratched my previous answer because I went
    back and re-read your problem. By what you typed
    DetailedTable.setDefaultRenderer(String.class,newDetailTableCellRenderer());
    it seems you're trying to set the default renderer on
    the Class. You can't do that - you have to set
    the renderer on the instance of the class:
    DetailedTable t = new DetailedTable(); // assuming
    DetailedTable is a sub-class of
    // JTable (why,
    // JTable (why, I don't know)
    t.setDefaultRenderer(String.class,new
    DetailTableCellRenderer());If this is not the case and DetailedTable is
    the instance, then I've always done this:
    detailedTable.getColumn(cName).setCellRenderer(new
    DetailTableCellRenderer());
    Hi, thanks for the reply...detailedtable is an instance of JTable not a subclass...
    i have tried doing the getColumn(cName) before, but it also does not seem to work...when i do that with, say, column 0, i cant select anything in column 0 and it doesnt work anyway...also, if i want this feature for the whole table, should i have multiple calls to this getColumn function with different cNames?
    thanks...
    Sid

  • JTabbedPane Cell Renderer problem

    Hi
    I have a JTabbedPane with two tabs both of which contain JTables with custom cell renderers. When i tab beteewn these tables the rendering gets "messed up". If I click on the table or alt tab between the application window and another window the table seems to right itself. I Have tried to call a repaint when switching tabs but this does not ssem to help... Can anyone help me please?

    [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]How to Use Tables
    If your code works on a normal table, it should make no difference that you have two different tables on two different tabs. So the problem is with you code and we have no idea what your code looks like.

  • JComboBox table cell renderer problem

    The following program demonstrates a difference in behavior of table cell editor combobox based on whether the combo box is editable or not. If the ComboBox is editable, then the first click into the table cell starts the edit and shows the popup, whereas if the combobox is not editable then it takes 2 clicks into the cell to cause the popup to become visible. I am trying to achieve the 1 click popup behavior while keeping the combobox not editable. Run the following program, and click on various cells, the top table requires 2 clicks for a popup, and the bottom table only 1. The only difference is the editablility of the combobox. (This is windows l&f)
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    public class JTableComboBoxCellEditorTest {
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e){e.printStackTrace();}
              DefaultTableModel tableModel = new DefaultTableModel(
                        new Object[][] {{"1","2"},{"2","3"},{"3","1"} },
                        new Object[]{"Column1","Column2"}
              final JComboBox renderer = new JComboBox(new Object[]{"1","2","3"});
              TableCellRenderer cellRenderer = new TableCellRenderer() {
                   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col){
                        renderer.setSelectedItem(value);
                        return renderer;
              JTable table1 = new JTable(tableModel);
              final JComboBox badEditor = new JComboBox(new Object[]{"1","2","3"});
              badEditor.setEditable(false);
              table1.setDefaultEditor(Object.class, new DefaultCellEditor(badEditor));
              table1.setDefaultRenderer(Object.class, cellRenderer);
              table1.setRowHeight(24);
              JTable table2 = new JTable(tableModel);
              final JComboBox goodEditor = new JComboBox(new Object[]{"1","2","3"});
              goodEditor.setEditable(true);
              table2.setDefaultEditor(Object.class, new DefaultCellEditor(goodEditor));
              table2.setRowHeight(24);
              table2.setDefaultRenderer(Object.class, cellRenderer);
              JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT,new JScrollPane(table1), new JScrollPane(table2));
            JFrame f = new JFrame("Table Test");
            f.getContentPane().add(split,BorderLayout.CENTER);
                f.setBounds(100,100,500,500);
            f.addWindowListener(new WindowAdapter() {
                 public void windowClosing(WindowEvent e) {
                      System.exit(0);
            f.setVisible(true);
    }

    Setting a renderer for first column:
    assetTable.getColumnModel().getColumn(1).setRenderer(tableRenderer);Your custom renderer must honor the selection color and border or otherwise the first column will not look selected. You should subclass DefaultTableCellRenderer:
    public class AssesTableRenderer extends DefaultTableCellRenderer  {
      public Component getTableCellRendererComponent(...) {
        // default renderer uses a label
        JLabel label = (JLabel)super.getTableCellRendererComponent(...);
        // decide icon to use
        Icon icon = ...;
        label.setIcon(icon);
       return label;
    }

  • JTable Cell Renderer Problem

    I have been reading a lot about cell renderers, and I realize this is beating a dead horse, and it should be simple, but it is still giving me fits.
    I am simply saving data from a JTable to a database. As I process each row, I would like to turn the quantity cell background to green to indicate it has been saved to the database.
    So here is the save loop:
                   for(int x = startRow; x < endRow; x++)
                        String prodCode = (String)inventoryModel.getValueAt(x, 0);
                        String qty = (String)inventoryModel.getValueAt(x, 6);
                        String ucost = (String)inventoryModel.getValueAt(x, 8);
                        Double levelDbl = Double.valueOf(qty);
                        Double ucostDbl = Double.valueOf(ucost);
                        levels.addLevel(prodCode, levelDbl.doubleValue(), dateString, period, ucostDbl.doubleValue());
                        inventoryTable.setRowSelectionAllowed(false);
                        inventoryTable.setColumnSelectionAllowed(false);
                        inventoryTable.changeSelection(x, 6, false, false);
                        System.out.println("Selected Row: " + inventoryTable.getSelectedRow() + "  Col: " +inventoryTable.getSelectedColumn());
                        int col = 6;
                        TableColumn tableCol = inventoryTable.getColumnModel().getColumn(col);
                        tableCol.setCellRenderer(new InventoryTableCellRenderer());
                        inventoryTable.validate();
                   }And here is the renderer:
         public class InventoryTableCellRenderer extends DefaultTableCellRenderer
              public Component getTableCellRendererComponent
                   (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
                   System.out.println("Value: " + value + "  isSelected: " + isSelected + "  hasFocus: " + hasFocus);
                   Component cell = super.getTableCellRendererComponent
                        (table, value, isSelected, hasFocus, row, col);
                   cell.setBackground(Color.green);
                   return cell;
         }This does not work, and here is the output from my printf statements:
    Selected Row: 0 Col: 6
    Selected Row: 1 Col: 6
    Selected Row: 2 Col: 6
    Value: 5.0 isSelected: false hasFocus: false
    Value: 5.0 isSelected: false hasFocus: false
    Value: 5.0 isSelected: false hasFocus: false
    If anyone has time (yeah right) I could use some help.
    Thanx
    Steve

    Hi, Im not all that skilled with JTable, I know that this changes the colors of all the cells in the JTable though.
    Perhaps you can continue from there?
    JTable table = new JTable() {
         @Override
         public Component prepareRenderer(TableCellRenderer renderer, int row, int column){
              Component c = super.prepareRenderer(renderer, row, column);
              c.setBackground(Color.GREEN );
              return c;
    };

  • JTree Cell Renderer Problem

    Hi can someone help me please??
    I've created a JTree with a custom TreeUI which paints the JTree's backround with gradient paint.
    The problem i'm having is that i want to make the background color of the treecells transparent, no color at all. In my custom TreeCellRenderer it works fine setting the foreground color and everything, but not the background...
    Any clues anyone?

    Figured it out right after this post :)
    I had to do the following in my cellrenderer
    setBackgroundNonSelectionColor(new Color(0, 0, 0, 0));As a parameter I sent a color object with a alpha level of 0 (completly transparent)...

  • 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

  • Row Selection problem in custom cell renderer

    Hi,
    I have created a custom cell renderer to set color in my table based on some value and the screen also shows colors when i set this cell renderer.
    But, I am not able to see the row selection ie. with blue background when I select any row in the table is nor appearing. Can you tell me how to solve this problem.
    Regards,
    R.Vishnu Varadhan.

    Check out this [url http://forum.java.sun.com/thread.jsp?forum=57&thread=507001]thread for a similiar example.

  • Event Handling in JTable Custom Cell Renderer

    I have a JLabel as a custom cell Renderer for a column. I want to handle mouse click event for the JLabel rendered in the cell.
    I tried adding the listener for the label in the custom cell renderer but it is not working. Any ideas how to handle this problem??
    Thanks
    S.Anand

    If you want to handle the selection of a tree node
    1) write a class like:
    public class TreePaneListener implements TreeSelectionListener {
    // TREE SELECTION LISTENER
    public void valueChanged(TreeSelectionEvent e) {
    JTree tree = (JTree)e.getSource();
    DefaultMutableTreeNode node = null;
    int count = 0;
    boolean doSomething = false;
    if(tree.getSelectionCount() > 1) {
         TreePath[] selection = tree.getSelectionPaths();
         int[] temp = new int[selection.length];
         for(int i =0; i < selection.length; i++) {
    // Check each node for selection
         node = (DefaultMutableTreeNode)selection.getLastPathComponent();
         if(node.getLevel()==2) {
    // Change this code to take the action desired
         doSomething = true;
    2) After creating the tree register the listener
    TreePaneListener handler = new TreePaneListener();
    tree.addTreeSelectionListener(handler);

  • How to display multiple JComponents in a tree cell renderer

    I have an object in a tree cell renderer and want to display its members(three members) status in a JTree as checkboxes such that each node displays three checkboxex with member-names and a node name. i tried using a JPanel and adding three labels into this panel to be returned for the cell renderer but the GUI fails to paint the node componnents. However on clicking the node the component which isn't visible displays correctly. please Help me out

    Since you didn't provide any sample code, it's all about wild guesses on what your problem is. The following code shows the type of program you could have posted :import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    public class TestTree extends JPanel {
         private static class MyCell {
              String theCellName;
              boolean theFirstField;
              boolean theSecondField;
              boolean theThirdField;
              public MyCell(String aName, boolean firstField, boolean secondField, boolean thirdField) {
                   theCellName = aName;
                   theFirstField = firstField;
                   theSecondField = secondField;
                   theThirdField = thirdField;
         private static class MyTreeCellRenderer extends JPanel implements TreeCellRenderer {
              private JLabel theCellNameLabel;
              private JCheckBox theFirstCheckBox;
              private JCheckBox theSecondCheckBox;
              private JCheckBox theThirdCheckBox;
              private DefaultTreeCellRenderer theDelegate;
              public MyTreeCellRenderer() {
                   super(new GridLayout(4, 1));
                   theCellNameLabel = new JLabel();
                   add(theCellNameLabel);
                   theFirstCheckBox = new JCheckBox("firstField");
                   add(theFirstCheckBox);
                   theSecondCheckBox = new JCheckBox("secondField");
                   add(theSecondCheckBox);
                   theThirdCheckBox = new JCheckBox("thirdField");
                   add(theThirdCheckBox);
                   theDelegate = new DefaultTreeCellRenderer();
                   setOpaque(true);
              public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                                                                       boolean expanded, boolean leaf, int row, boolean hasFocus) {
                   if (!(value instanceof DefaultMutableTreeNode)) {
                        return theDelegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
                   Object userObject = ((DefaultMutableTreeNode)value).getUserObject();
                   if (!(userObject instanceof MyCell)) {
                        return theDelegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
                   setBackground(tree.getBackground());
                   if (selected) {
                        setBorder(BorderFactory.createLineBorder(Color.BLUE, 2));
                   } else {
                        setBorder(BorderFactory.createLineBorder(getBackground(), 2));
                   MyCell cell = (MyCell)userObject;
                   theCellNameLabel.setText(cell.theCellName);
                   theFirstCheckBox.setSelected(cell.theFirstField);
                   theSecondCheckBox.setSelected(cell.theSecondField);
                   theThirdCheckBox.setSelected(cell.theThirdField);
                   return this;
              public Component add(Component comp) {
                   if (comp instanceof JComponent) {
                        ((JComponent)comp).setOpaque(false);
                   return super.add(comp);
         public TestTree() {
              super(new BorderLayout());
              JTree tree = new JTree(createModel());
              tree.setShowsRootHandles(true);
              tree.setCellRenderer(new MyTreeCellRenderer());
              add(new JScrollPane(tree), BorderLayout.CENTER);
         private static final TreeModel createModel() {
              DefaultMutableTreeNode root = new DefaultMutableTreeNode(new MyCell("root", true, true, true));
              DefaultMutableTreeNode child1 = new DefaultMutableTreeNode(new MyCell("child1", false, true, false));
              DefaultMutableTreeNode child2 = new DefaultMutableTreeNode(new MyCell("child2", false, false, true));
              root.add(child1);
              root.add(child2);
              return new DefaultTreeModel(root);
         public static void main(String[] args) {
              final JFrame frame = new JFrame("Test");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(new TestTree());
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.setSize(600, 400);
                        frame.show();
    }

  • Tree Cell Renderer settings for displaying complete text.

    I have a tree model. It is of the form
    abc (123.00)
    -----def (456.00)
    ----------ghi (678.00)
    But it is displayed like
    abc (12...
    -----def (45..
    ----------ghi (67..
    I don't want the numbers in the end to be missing. It is a problem for the user to expand them everytime.
    I am using, JTree and using my cell renderer, with following properties in
    super.getTreeCellRendererComponent(tree, false, X, false, false, row, false);I did try to change it to
    super.getTreeCellRendererComponent(tree, false, X, TRUE, false, row, false);but still no success.
    My function toString() for tree elements looks like this
                     double u = "123.00";
                     String num = String.format("%.2f", u);
                     return getName() + " (" + num  + ")";Can you please suggest possible way around for this?

    package abc;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.WindowConstants;
    import javax.swing.JFrame;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeSelectionModel;
    public class NewJPanel extends javax.swing.JPanel implements MouseListener {
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              frame.getContentPane().add(new NewJPanel());
              frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
         JTree m_tree;
        private JScrollPane myPane;
        float multi = 1;
        DefaultTreeModel tree = new DefaultTreeModel(new ContainerNode("root"));
        DefaultMutableTreeNode parent = (DefaultMutableTreeNode)tree.getRoot();
         public NewJPanel() {
            super(new BorderLayout());
            String util = String.format("%.2f", 123456789012345679801234567980.00);
            util = "abc" + " (" + util  + ")";
                DefaultMutableTreeNode e = new DefaultMutableTreeNode(util);
                tree.insertNodeInto(e, parent, 0);
            m_tree = new JTree(tree);
            m_tree.setEditable(false);
            m_tree.setDragEnabled(false);
            m_tree.getSelectionModel().setSelectionMode(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
            m_tree.setAutoscrolls(true);
            m_tree.setPreferredSize(new java.awt.Dimension(397, 297));
            myPane = new JScrollPane(m_tree);
            myPane.setAutoscrolls(true);
            myPane.getVerticalScrollBar().setAutoscrolls(true);
            add(myPane, BorderLayout.CENTER);
            m_tree.addMouseListener(this);
              initGUI();
         private void initGUI() {
              try {
                   setPreferredSize(new Dimension(400, 300));
              } catch (Exception e) {
                   e.printStackTrace();
         public void mouseClicked(MouseEvent e) {
              String util = String.format("%f", 6546464642345679801234567980.00 * multi);
            util = "abc" + " (" + util  + ")";
            DefaultMutableTreeNode child = (DefaultMutableTreeNode) parent.getChildAt(0);
            child.setUserObject(util);
            m_tree.repaint();
         public void mouseEntered(MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         public void mousePressed(MouseEvent e) {}
         public void mouseReleased(MouseEvent e) {}
    class ContainerNode extends DefaultMutableTreeNode
        private static final long serialVersionUID = 14;
        ContainerNode(String s)
        { super(s); }
    }Executing this code... clicking in the panel, changes the number.
    The new number is displayed as (65464646423456798000000000.000.......
    My problem is nearly similar, except that in my code I am using, String.format("%.2f", 6546464642345679801234567980.00 * multi);
    and still I get (65...)

Maybe you are looking for

  • Same font appears different in two systems

    The problem principally lies with transaction MM03 (Material Master - Display). The material description in "Additional Data" tab in any Material View is appearing to be of different fonts in two different client systems. Upon checking, I found that

  • I've lost my scrollbar in my inbox. how do I get it back

    I downloaded firefox 3.6 and now I've lost the vertical scrollbar on my inbox. How do I get it back. This seems to happen everytime I download a newer version.

  • Bug in Netbeans Java compiler?

    I think Netbeans (or Java itself?) has a major flaw in its compiler design. Explain to me why the following code is not compilable. Specifically, why it should complain about line 8: cannot find symbol symbol : variable Selected When I clearly declar

  • Payment Sytem Unavailable

    I'm trying to purchase a monthly PS subscription after letting my previous expire.  When I get to purchase now page and click on Purchase button it says that "payment system unavailable" and to try back.  I've tried for multiple days now, facing a de

  • Entry with tax rates

    Experts_ I have one of information about my related issue i.e suppose one sales transaction is CENVAT applicable, at that (BED,) VAT, is applicable, so at with in the STATE, what are the rates are applicable, State to state , what are rates applicabl