Selection of Custom JTable cell renderer inconsistenent between LAFs

Sorry if that seems cryptic, but I don't know if I've run into a bug or not. I've recently switched from windows to linux and have noticed a problem with one of my programs. I have a "multiline" renderer that I made for my JTable. The renderer isn't terribly elegant, but when I'd select the row of the table, I made the multi-line renderer change its colors in response to the selection.
This color selection switching works fine under the Metal LAF and the Windows LAF. However, this no longer works in the default look and feel is for linux (GTK+???). My multiline renderer in the JTable won't change its foreground/background in response to selection, but will if I use the Metal LAF under linux.
Any idea what I'm doing wrong? Is this a bug? (I'm fairly certain I'm doing something silly, I just can't see it for the life of me).
Here's the code I use to update the selection:
class MultilineRenderer extends JTextArea
        implements TableCellRenderer {
    public MultilineRenderer(){
        super();
        setWrapStyleWord(false);
        setLineWrap(true);
        setFont(Const.TABLE_FONT);
        setOpaque(true);
    public Component getTableCellRendererComponent(
            JTable table, Object text,
            boolean isSelected, boolean hasFocus,
            int row, int column) {
        String data = (String)text;
        setText(data);
        if (isSelected){
            setForeground(table.getSelectionForeground());;
            setBackground(table.getSelectionBackground());
        } else {
            setForeground(table.getForeground());
            setBackground(table.getBackground());
        return this;
}

Some look and feels will ignore calls to setBackground and setForeground, and will instead decide their own colour.
To quote the API documentation:
"The background color affects each component differently and the parts of the component that are affected by the background color may differ between operating systems."
I would imagine that this is your problem. Annoying, I know!

Similar Messages

  • Custom JTable cell editor problem

    I have a custom JTable cell editor which is a JPanel with 2 JtextFields, One for a name, the other for a data value. My problem lies in when the the cell is selected and then the user start typing. The JTextfield outline shows up, but there is no carat. I can only edit the cell when I click the mouse in it again. I have my isCellEditable method set to only allow editing on 2 mouse clicks, but I did try it with just returning true and had the same problem. Please help.
    Code:
    class cellValue {
    String name;
    String data;
    Color nameColor;
    Color dataColor;
    Font font;
    public cellValue(String n, String d, Color nC, Color dC, Font ff){
    name = n;
    data = d;
    nameColor = nC;
    dataColor = dC;
    font = ff;
    } //end class
    public class TextFieldCellEditor extends JPanel implements TableCellRenderer, TableCellEditor{
    private EventListenerList listenerList = new EventListenerList();
    private ChangeEvent event = new ChangeEvent(this);
    private cellValue s;
    private int e_row=0;
    private int e_col=0;
    private JTextField ta;
    private JTextField tb;
    public TextFieldCellEditor() {
    setLayout(new GridBagLayout());
    ta = new JTextField();
    tb = new JTextField();
    tb.setHorizontalAlignment(SwingConstants.RIGHT);
    add(ta, new GridBagConstraints(0,0,1,1,0.6,0.0,java.awt.GridBagConstraints.WEST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    add(new JLabel(" "),new GridBagConstraints(1,0,1,1,0.1,0.0,java.awt.GridBagConstraints.WEST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    add(tb, new GridBagConstraints(2,0,1,1,0.3,0.0,java.awt.GridBagConstraints.EAST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    } //end init
    public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected,
    boolean hasFocus,int row, int column) {
    s = (cellValue)value;
    e_row = row;
    e_col = column;
    ta.setText(s.name);
    tb.setText(s.data);
    ta.setFont(s.font);
    tb.setFont(s.font);
    ta.setForeground(s.nameColor);
    tb.setForeground(s.dataColor);
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    ta.setBackground(table.getBackground());
    tb.setBackground(table.getBackground());
    ta.setCaretColor(Color.WHITE);
    tb.setCaretColor(Color.WHITE);
    return (JComponent)(this);
    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 e) {
    if (e instanceof MouseEvent) {
    return ((MouseEvent)e).getClickCount() >= 2;
    } return true;
    // 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){
    try {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {requestFocus();}
    } catch (Exception e) {};
    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);
    } //end class

    Thanks again for the repley.
    I tried removing the celleditorlistener and using the setSurrenderFocusOnKeystroke, but it did not work. The textfield is editable;
    I did change:
    public void addCellEditorListener(CellEditorListener l){
    try {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {ta.requestFocus();}
    } catch (Exception e) {};
    listenerList.add(CellEditorListener.class, l);
    }This allows the first textfield to request focus and this seems to work. But when I highlight a cell, then start typing, the first character I type puts me into the editor, but it is lost. Example:
    I type hello
    and get ello in the cell. Then when I press enter the input is excepted and the selection goes to the next cell, but I cannot move the Highlight cursor at all, seems locked. The only way I can continue to the next cell is to use the mouse.
    You said you had a cell editor working. Would you care to share as an example. This is killing me to get this to work properly.
    Thanks again
    Dave

  • Custom table cell renderer in a JTable is not called

    Hello, all,
    I have the following task: I need to select several cells in a column, change the value of those cells, and once the value changes, the color of these cells should change as well. I wrote a custom cell renderer, and registered it for the object type that will use it to render the cell. However, the custom cell renderer is never called. Instead, the class name of the object is displayed in the cell.
    My code snippents are as follows:
    //Declare the table and add custom cell renderer
    JTable table = new JTable (7,7);
    table.setCellSelectionEnabled (true);
    table.setSelectionMode (ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    //Add the custom cell renderer to render objects of type Item
    table.setDefaultRenderer(Item.class, new CustomTableCellRenderer());
    //Get the selected cells and change the object type in those cells
    //This part works, since I see the app entering the for loop in the debugger, and the item.toString() value is displayed in each selected cell
    int rowIndexStart = table.getSelectedRow();
    int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
    int colIndex = table.getSelectedColumn();
    Item item = new Item ();
    for (int i = rowIndexStart; i<=rowIndexEnd; i++){
                  table.setValueAt(item, i, colIndex);
                 //I expect the cell to redraw now using custom cell renderer defined below, but that cell render is never called.  Instead, the item.toString() value is displayed in the cell.   What is wrong?
    //Definition of custom cell renderer. 
    //the getTableCellRendererComponent is never called, since the System.out.println never prints.  I expected this method to be called as soon as the Item object is added to the cell.  Am I wrong in expecting that?
    class CustomTableCellRenderer extends DefaultTableCellRenderer  {
        public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component cell = super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column);
            System.out.println("value: "+value.getClass()+" isSelected "+isSelected+" hasFocus "+hasFocus+" row "+row+" col "+column);
            if (this.isFocusOwner()) {
            cell.setBackground( Color.red );
            cell.setForeground( Color.white );
            return cell;
    } Please, help,
    Thank you!
    Elana

    The suggestion given above assumes that all the data in a given column is of the same type.
    If you have different types of data in different rows the you should be overriding the getCellRenderer(...) method. Something like:
    public TableCellRenderer getCellRenderer(int row, int column)
        Object o = getValueAt(row, column);
        if (o instanceof Item)
            return yourCustomRenderer
        else
            return super.getCellRenderer(row, column);
    }

  • Custom Table Cell Renderer Unable To Set Horizontal Alignment

    Hello,
    I have a problem that I'm at my wit's end with, and I was hoping for some help.
    I need to render the cells in my table differently (alignment, colors, etc) depending on the row AND the column, not just the column. I've got this working just fine, except for changing the cell's horizontal alignment won't work.
    I have a CustomCellRenderer that extends DefaultTableCellRenderer and overrides the getTableCellRendererComponent() method, setting the foreground/background colors and horizontal alignment of the cell based on the cell's value.
    I have a CustomTable that extends JTable and overrides the getCellRenderer(int row, int column) method to return a private instance of this CustomCellRenderer.
    This works fine for foreground/background colors, but my calls to setHorizontalAlignment() in the getTableCellRendererComponent() seem to have no effect, every cell is always displayed LEFT aligned! It's almost like the cell's alignment is determined by something else than the table.getCellRenderer(row,column).getTableCellRendererComponent() method.
    I've also tried setting the renderer for every existing TableColumn in the TableModel to this custom renderer, as well as overriding the table's getDefaultColumn() method to return this custom renderer as well for any Class parameter, with no success.
    No matter what I've tried, I can customize the cell however I want, EXCEPT for the horizontal alignment!!!
    Any ideas???
    Here's the core custom classes that I'm using:
    class CustomTable extends JTable {
    private CustomRenderer customRenderer = new CustomRenderer();
    public CustomTable() {
    super();
    public TableCellRenderer getCellRenderer(int row, int column) {
    return customRenderer;
    } // end class CustomTable
    class CustomRenderer extends DefaultTableCellRenderer {
    public CustomRenderer() {
    super();
    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 % 2 == 0) {
    setForeground(Color.red);
    setHorizontalAlignment(RIGHT);
    } else {
    setForeground(Color.blue);
    setHorizontalAlignment(LEFT);
    return this;
    } // end class CustomRenderer
    Even worse, I've gotten this to work fine in a trivial example I made to try and re-create the problem. But for some reason, this same thing is just not working for horizontal alignment in my actual project?!?
    Anyone have any ideas how the cell's horizontal alignment set in the getTableCellRendererComponent() method is being ignored or overwritten before the cell is being displayed???
    Thanks, any help is appreciated,
    -Alex Blume

    Ok, so I've looked into their source and I think I know where and what the trouble is. The JTable.java has a method called:
    3658> public TableCellRenderer getCellRenderer(int row, int column) {
    3659> TableColumn tableColumn = getColumnModel().getColumn(column);
    3660> TableCellRenderer renderer = tableColumn.getCellRenderer();
    3661> if (renderer == null) {
    3662> renderer = getDefaultRenderer(getColumnClass(column));
    3663> }
    3664> return renderer;
    3665> }
    starting at line 3658 of their source code. It retrieves the TableCellRenderer on line 3660 by calling the tableColumn's getCellRenderer method. This is found in the TableColumn.java class:
    421> public TableCellRenderer getCellRenderer() {
    422> return cellRenderer;
    423> }
    See the problem? Only ONE cell Renderer. It's referring to a variable found at line 140 which is of type TableCellRenderer ... well actually it's created as a DefaultTableCellRenderer at some point since TableCellRenderer is an interface.
    Basically the fix is this:
    In the TableColumn.java file, a collection (Vector, LinkedList, whatever) needs to keep track of each cell's renderer. This will solve the solution. Of course this will be something that you or I can make.
    What's funny is the contradiction in documentation between JTable's and TableColumn's getCellRenderer() method. First, if we look at TableColumn's documentation it states:
    "Returns the TableCellRenderer used by the JTable to draw values for this column."
    Based on that first statement, the getCellRenderer() method in TableColumn is doing its job exactly. No lies, no contradictions in what it does.
    However, that method is called up inside of the JTable's getCellRenderer() method which says a completely different thing which is:
    "Returns an appropriate renderer for the cell specified by this row and column."
    Now we have a problem. For the cell specified. It appears that the rush to push this out blinded some developer who either:
    1) mis-interpreted what the JTable getCellRenderer() method was supposed to do and inadvertently added a feature or;
    2) was in a 2 a.m. blitz, wired on Pepsi and adrenalin and wrote the bug in.
    Either way, I'm really hoping that they'll fix this because it will take care of at least 2 bugs. Btw, anyone interested in posting a subclass to solve this problem (subclass of TableColumn) is more than welcome. I've spent much too much time on this and my project is already behind so I can't really afford any more time on this.
    later,
    a.

  • Problem in JTable cell renderer

    Hi
    One problem in JTable cell. Actually I am using two tables while I am writing renderer for word raping in first table .. but it is affected in last column only remain is not being effected�. Please chaek it out what is exact I am missing�
    Thanks
    package com.apsiva.tryrowmerge;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.EventObject;
    import java.util.Hashtable;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.border.Border;
    import javax.swing.border.EmptyBorder;
    import javax.swing.event.*;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    class Item_Details extends JFrame {
        ApsJTable itemTable = null;
         ApsJTable imageTable = null;     
         ArrayList data = new ArrayList();
         String[] columns = new String[2];
         ArrayList data1 = new ArrayList();
         String[] columns1 = new String[2];
         ItemTableModel itemTableModel = null;
         ItemTableModel itemTableModel1 = null;
         public Item_Details()
              super("Item Details");          
             this.setSize(600,100);
             this.setBackground(Color.WHITE);
              this.setVisible(true);
             init();          
         private void init(){
              ////////////// Get data for first Table Model  ////////////////////////////
              data = getRowData();
              columns = getColData();
              System.out.println(columns[0]);
             itemTableModel = new ItemTableModel(data,columns);
             /////////////Get Data for Second Table Model //////////////////////////////
              try{
                        data1 = getRowData1();
                 }catch(Exception e){}
              columns1 = getColumns1();
             itemTableModel1 = new ItemTableModel(data1,columns1);
             ///////////// Set Data In Both Table Model //////////////////////////////////
              itemTable = new ApsJTable(itemTableModel);
              imageTable = new ApsJTable(itemTableModel1);
              this.itemTable.setShowGrid(false);
              this.imageTable.setShowGrid(false);
              this.itemTable.setColumnSelectionAllowed(false);
              this.imageTable.setColumnSelectionAllowed(false);
              System.out.println(itemTable.getColumnCount());
              this.imageTable.setRowHeight(getImageHeight()+3);
              JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              tableScrollPane.setRowHeaderView(this.itemTable);
              //itemTable.getColumnModel().getColumn(0).setMaxWidth(200);
              itemTable.getColumnModel().getColumn(0).setPreferredWidth(200);
              itemTable.getColumnModel().getColumn(1).setPreferredWidth(600);
              tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
              itemTable.getTableHeader().setResizingAllowed(false);
              itemTable.getTableHeader().setReorderingAllowed(false);
              itemTable.setColumnSelectionAllowed(false);
              //itemTable.setRowHeight(25);
              itemTable.setCellSelectionEnabled(false);
              itemTable.setFocusable(false);
              imageTable.getTableHeader().setReorderingAllowed(false);
              imageTable.setFocusable(false);
              imageTable.setCellSelectionEnabled(false);
              //tableScrollPane.setOpaque(false);
              itemTable.setAutoCreateColumnsFromModel(false);
              int columnCount = itemTable.getColumnCount();
              for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();     // NEW
              //     editor = new TextAreaCellEditor();     
              //     TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
                   System.out.println(k);
                   itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);          
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(editor);
                   /*itemTable.getColumnModel().getColumn(1).setCellRenderer(new TextAreaCellRenderer());
                   itemTable.getColumnModel().getColumn(1).setCellEditor(new TextAreaCellEditor());*/
    //               itemTable.setShowGrid(false);
                   //itemTable.addColumn(column);
                   //itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
    ////////////---------------------- Here background color is being set--------------//////////////////
              this.imageTable.getParent().setBackground(Color.WHITE);
              this.itemTable.getParent().setBackground(Color.WHITE);
              tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
              getContentPane().add(tableScrollPane,BorderLayout.CENTER);
              getContentPane().setVisible(true);
         public static void main(String[] str){
              com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
              try {
                javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
                javax.swing.UIManager.setLookAndFeel(alloyLnF);
              } catch (javax.swing.UnsupportedLookAndFeelException ex) {
              ex.printStackTrace();
              Item_Details ID = new Item_Details();
              ID.setVisible(true);
    public ArrayList getRowData()
         ArrayList rowData=new ArrayList();
         Hashtable item = new Hashtable();
         item.put(new Long(0),new String("Item No:aaaaaaa aaaaaaaa aaaaaaaaa aaaaaa"));
         item.put(new Long(1),new String("RED-1050"));
         rowData.add(0,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Description:rt r trtrt rttrytrr tytry trytry tr tr rty thyjyhjhnhnhgg hhjhgjh"));
         item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
         rowData.add(1,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Stage:"));
         item.put(new Long(1),new String("Draft"));
         rowData.add(2,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Price: "));
         item.put(new Long(1),new String("999.00"));
         rowData.add(3,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(4,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(5,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(6,item);
         /*item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(5,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(6,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(7,item);
         return rowData;
    public String[] getColData()
         String[] colData = new String[]{"Attribute","Value"};
         return colData;
    public ArrayList getRowData1()throws MalformedURLException{
         ArrayList rowData = new ArrayList();
         Hashtable item = new Hashtable();
         String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url = new URL(str);
         ImageIcon ic = new ImageIcon(url);
         ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
         item.put(new Long(0), scaledImage);
         rowData.add(0,item);
         String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url1 = new URL(str1);
         ImageIcon ic1 = new ImageIcon(url1);
         ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
         item.put(new Long(0),scaledImage1);
         rowData.add(1,item);
         return rowData;
    public String[] getColumns1(){
         String[] colData = new String[]{"Image"}; 
         return colData;
    public int getImageHeight(){
         ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
         return ic.getIconHeight();
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;

    I think Problem is between these code only
    for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();
                                                                itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);or in this renderer
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;
    }

  • Which decide the JTable cell renderer behavior

    Hi,
    I have a subclass of JTable in which I overwrite the JTable.valueChanged() function ( which is used to implement the ListSelectionListener)
    I have called setCellSelectionEnabled(true); to enable only the cell selection
    I find if I don't call super.valueChanged() in myTable. valueChanged() method, the table rendering is in correct. For example,
    first I select cell at row=2, col=3 (2, 3),
    the cell get rendered.
    then I select cell (0,3).
    I find no any cell get rerendered.
    but I hope this time the previous selected cell and the new selected cell are re-rendered.
    This problem only happens on the same column.
    If I first select cell (2,3) then select cell (2,5), then both of these cell get rerendered as I want.
    However, If I call super.valueChanged(), all the cell re-render works fine.
    I can see in the JTable.valueChanged(), it has varibles as:
    lastSelectedRow, lastSelectedCol, but I don't find them used in any tableCellRenderer.
    I wonder where in the JTable code or any related code it call the table cell renderer when cell selection changed?
    Thanks

    I overwrite the JTable.valueChanged() function ( which is used to implement the ListSelectionListener)I would think you should use the getSelectionModel() method and then add a ListSelectionListener to the selection model.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
    see http://homepage1.nifty.com/algafield/sscce.html,
    that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the "Code Formatting Tags",
    see http://forum.java.sun.com/help.jspa?sec=formatting,
    so the posted code retains its original formatting.

  • JTable cell rendering lag

    I've got a JTable for which I wrote a custom CellRenderer that extends JLabel. For each cell, I set the icon for the JLabel that is going to be rendered in the cell. The icon is a gif with some transparent elements. So I set the JLabel to opaque and set the background color so it will show through in the transparent areas. Works like I intended it to, but there's a lag. The table I have has enough rows to scroll well beyond the JScrollPane that it's in. When I scroll down the table, all the cells show up briefly as only the background color, then change quickly to the icon that is in the JLabel. So when I scroll, the entire table seems to be the background color without any icons. When I stop scrolling, the icons fill in pretty quick. But it's disconcerting when scrolling. Once a certain region (set of rows) has been scrolled to once, the problem doesn't happen if you scroll away and then back to that same region.
    Thanks.
    ab.

    I had considered that and eliminated that route through some testing.
    I did sort of figure out what the problem is, but don't yet have a solution. The table I'm rendering has variable height rows. Even rows are one height, odd rows another height. In my custom renderer, I modify the row heights as:
              if (getTable() != null)
                   if (row % 2 == 0)
                        if(CommonStyle.SUMMARY_ROW_HEIGHT != getTable().getRowHeight(row))
                             getTable().setRowHeight(row, CommonStyle.SUMMARY_ROW_HEIGHT);
                   else
                        if(CommonStyle.ARROW_ROW_HEIGHT != getTable().getRowHeight(row))
                             getTable().setRowHeight(row, CommonStyle.ARROW_ROW_HEIGHT);
              }Turns out changing the row heights during the rendering process is what's causing the lag, perhaps there is some table structure changing event that I need to catch and suppress. I've got some optimization code in the cell renderer to no-op the repaint and property change events. I'll let you know what I find.
    Thanks.
    ab.

  • Customized JTable cell

    Hello there:
    I want to customize the JTable cell which combines a textfield and a label. other than that, it will behave like any other Jtable component. I wrote a sample class as below, it looks ok but acts weird. Most likely my customized renderer is wrong, anyone pls revise it? thanks a lot!
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.BorderFactory;
    import javax.swing.BoxLayout;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.TableCellRenderer;
    public class CustomizedTable extends JFrame {
    * @param args
    CustomizedTable(){
    String[] col = new String[]{
    "col1", "col2","col3"
    Object[][] data = {
    {"1","2","3"},
    {"1","2","3"},
    {"1","2","3"},
    {"1","2","3"}
    JTable table = new JTable(data,col);
    DataColumn dc = new DataColumn();
    table.setDefaultRenderer(table.getColumnClass(0),dc);
    table.setDefaultEditor(table.getColumnClass(0),dc);
    dc = new DataColumn();
    table.setDefaultRenderer(table.getColumnClass(1),dc);
    table.setDefaultEditor(table.getColumnClass(1),dc);
    dc = new DataColumn();
    table.setDefaultRenderer(table.getColumnClass(2),dc);
    table.setDefaultEditor(table.getColumnClass(2),dc);
    JScrollPane scroll = new JScrollPane(table);
    scroll.setPreferredSize (new Dimension(300,200));
    getContentPane().add(scroll, BorderLayout.CENTER);
    pack();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    new CustomizedTable();
    class DataColumn extends DefaultCellEditor implements TableCellRenderer {
    JFormattedTextField ftf;
    private JPanel panel = null;
    private JLabel l = new JLabel(" %");
    public DataColumn() {
    super(new JFormattedTextField());
    ftf = (JFormattedTextField) getComponent();
    ftf.setHorizontalAlignment(JTextField.RIGHT);
    ftf.setFocusLostBehavior(JFormattedTextField.PERSIST);
    ftf.setBorder(BorderFactory.createEmptyBorder());
    panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    panel.add(ftf);
    panel.add(l);
    public Component getTableCellRendererComponent(JTable table, Object o,
    boolean isSelected, boolean hasFocus, int row, int column) {
    ftf = (JFormattedTextField) getComponent();
    ftf.setHorizontalAlignment (JTextField.RIGHT);
    ftf.setFocusLostBehavior(JFormattedTextField.PERSIST);
    ftf.setBorder(BorderFactory.createEmptyBorder());
    //panel = new JPanel();
    //panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    //panel.add(ftf);
    //panel.add(l);
    return panel;
    public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int row, int column) {
    JFormattedTextField ftf = (JFormattedTextField) super
    .getTableCellEditorComponent(table, value, isSelected, row,
    column);
    ftf.setValue(value);
    // ftf.setBorder(BorderFactory.createEmptyBorder());
    // ftf.setHorizontalAlignment(JTextField.RIGHT);
    // panel = new JPanel();
    // panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    // panel.add(ftf);
    // panel.add(l);
    return panel;
    }

    After 40 postings you should know how to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags.

  • Custom Jtree Cell Renderer goes to infinite loopp...any suggestion???

    Hey ...thanks for you help before....
    Another problem..
    My Jtree works fine with default Cell Renderer .. but goes to infinite
    loop with CustomDefaultRenderer after few minutes...
    Any suggestions....
        public DynamicTree() {
            super(new GridLayout(1,0));
            rootNode = new DefaultMutableTreeNode("POSTINGS & SEARCHES");
            treeModel = new DefaultTreeModel(rootNode);
            treeModel.addTreeModelListener(new MyTreeModelListener());
            tree = new JTree(treeModel);
            tree.setEditable(false);
            tree.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setShowsRootHandles(true);
      //      tree.addMouseListener(ml);
      //      tree.addKeyListener(kl);
            JScrollPane scrollPane = new JScrollPane(tree);
            add(scrollPane);
            //          tree.setCellRenderer();
            tree.addTreeSelectionListener(new TreeSelectionListener(){
                public void valueChanged(TreeSelectionEvent evt){
                    System.out.println("Tree's lead selection path is " +
                            tree.getLeadSelectionPath());
            tree.setCellRenderer( new CustomDefaultRenderer());              
    public class CustomDefaultRenderer extends DefaultTreeCellRenderer {
        String suffix = null ;
        String prefix = null ;
        boolean expired = false;
        boolean matched = false ;
        PostingHandler pHandler = new PostingHandler();
        public Component getTreeCellRendererComponent(
                JTree tree,
                Object value,
                boolean sel,
                boolean expanded,
                boolean leaf,
                int row,
                boolean hasFocus) {
            super.getTreeCellRendererComponent(
                    tree, value, sel,
                    expanded, leaf, row,
                    hasFocus);
            suffix = (String)value.toString() ;
            try {
                prefix = value.toString().substring(0,value.toString().indexOf(":") + 1);
                suffix = suffix.substring(suffix.indexOf(":")+1,suffix.length());
                System.out.println("Prefix:"+prefix +"\tSufix :"+suffix);
            }catch (Exception e){System.out.println("Nothing to index yet" + e);}
            //    value = (Object)suffix;
            if(pHandler.newPostingsMatch.contains(prefix)) {
         //            if(hasFocus){pHandler.removePostingMatch(prefix);}               
                         setBackgroundNonSelectionColor(Color.CYAN);
            }else
                setBackgroundNonSelectionColor(Color.WHITE);
            System.out.println("Other <>values:\tValue" + value.toString() + "\tSEL:"+sel +"\tExpanded:" + "\tLEAF:"+leaf +
                    "\tRow:" +row + "\tfocus:"+hasFocus );
            return this;
        public void paintComponent(Graphics g){
            System.out.println("Paint is called");
            //g.drawLine(0, 0, 100, 100);
            if(expired){
                g.drawLine(22, 11, 100,11);
            g.drawString(suffix, 22,15);
            validate();
            repaint();
    }

    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)...

  • Customized table cell renderer doesn't work after table data model changed

    Hi:
    I have a jtable with a custimized table cell render (changes the row color). Everything works fine while the data model is unchanged. I can change the row color, etc. However, after I delete one row or any number of rows in the table, the data model is updated and the custmized table cell renderer is not being called anymore while jtable is rendering on its cells. Seems like the table cell render is no long associated with the jtable. Is this a known problem? Any help would be appreciated.
    Thanks

    I am having the same problem. Has anybody solved this issue?
    Thanks

  • 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

  • Disabling the border on JTable cell renderer

    Hello all
    I've developed a JTable that doesn't allow cell editing and only allows single-row selection. It works fine, I've allowed the user to press <tab> to select the next row or click the mouse to select any row. The row selected is high-lighted and I'm happy with how it works.
    However:
    Due to the single-row selection policy, it doesn't make sense to display a border around any cell that has been clicked. I would therefore like to prevent the JTable from displaying a border on any cell the user has clicked.
    I've checked out the API documentation for JTable and the closest I've been able to get is to construct a DefaultTableCellRenderer and then use JTable.setDefaultRenderer. The problem is I don't know how to set the DefaultTableCellRenderer to NOT display a border when selected.
    I can see a method called getTableCellRendererComponent which takes parameters that seemingly return a rendering component, but should I specify isSelected = true and isFocus = true? And what should I do once I have the Component? I've tried casting it to a JLabel and setBorder(null) on it, but the behaviour of the table remains the same.
    I've tried all sorts of things but to no avail. I'm finding it all a bit confusing...
    Why oh why isn't there simply a setTableCellRendererComponent()? ;)

    JTable can potentially use multiple renderers based on the type of data in each column, so you would need to create multiple custom renderers using the above approach. The following should work without creating custom renderers:
    table = new JTable( ... )
         public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
              Component c = super.prepareRenderer(renderer, row, column);
              ((JComponent)c).setBorder(null);
              return c;
    };

  • 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

  • Custom JTable cell editors and persistence

    I have a JTable with an underlying data model (an extension of AbstractTableModel) that uses custom cell editors in the last column. The cell editor in that column, for a given row, depends on the value selected in another column of the same row. The cell editors include text, date, list, and tree editors (the last one in a separate dialogue). The number of rows is changeable.
    I have need to persist the data for a populated table from time to time, for restoration later on. I've achieved that, such that the data model is recreated, the table appears correct, and the appropriate cell editors activated (by creating new instances of the editors' classes).
    However, my problem is that the (custom) cell editors do not reflect the data in the model when editing mode is begun the first time after restoration. Eg. the text editor is always empty, the list editor shows the first item, and no node is selected in the tree editor.
    If I've restored the model correctly, should the editors properly reflect the underlying data when they are set to editing mode?
    I suspected not, and thus tried to explicitly 'set' the correct values immediately after each editor is recreated ... but to no avail.
    Does anyone have any thoughts, or experience with something similar? I'm happy to supply code.

    You can use html tags within Swing, so I think you can do the following:
    * MyRenderer.java
    * Created on 26 April 2007, 10:27
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package newpackage;
    import java.awt.Component;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.SwingConstants;
    import javax.swing.table.TableCellRenderer;
    * @author CS781RJ
    public class MyRenderer extends JLabel implements TableCellRenderer
        public MyRenderer()
            setHorizontalTextPosition(SwingConstants.RIGHT);
            setIconTextGap(3);
            setOpaque(true);
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean cellHasFocus, int row, int column)
            if (isSelected)
                setBackground(table.getSelectionBackground());
                setForeground(table.getSelectionForeground());
            else
                setBackground(table.getBackground());
                setForeground(table.getForeground());
            if (value instanceof String)
                if ((value != null) && (value.toString().length() > 0))
                    System.out.println("Value: " + value.toString());
                    setFont(new java.awt.Font("Tahoma", 0, 11));
                    setText("<html>" + value.toString().replaceAll("\n", "<br>") + "</html>");
            return this;
    }In the class that has the JTable, use the code AFTER declaring the values, columns, etc:
    jTable1.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());
    jTable1.setValueAt("Riz\nJavaid", 0, 0);One thing I haven't done is to resize the cell heights, make sure this is done.
    Hope this helps
    Riz

  • 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

Maybe you are looking for

  • How to sync more than one iphone to a macbook?..

    How to sync more than one iphone to a macbook?..

  • Windows 8.1 pro WIFI issues

    After updating to windows 8.1 pro from windows 8.1 preview, wifi is showing "No internet access". no issue with router as it is working on other devices. Tried disable-enable. tried re install. tried updating driver. nothing seems to work. any help w

  • Decode null with function call

    Hi Is it possible to use decode in select for the below scenario, if so what is the correct syntax IF function one returns null I want to call display the value from function 2 in decode statement. Regards anna

  • Old domain controller crashed. Created a new one..having to rejoin computers to domain..easier way to do this?

    I had a single domain controller. It has crashed. I had to create a new domain controller with all the same existing information from the old server..same domain name, server name, and IP. Im having issues with desktops. Everything is setup on the se

  • Built-in iSight blurry with iChat

    When I use iChat my preview is clear and then goes blurry when I start to chat. I have tried extra and different lighting and iGlasses. I have also changed the video prefs in iChat to bandwidth limit is none. I think it might be my Quicktime prefs bu