0

My question is simple but I searched all over the internet and StackOverflow but not able to find out the perfect answer so I am here. I am creating a JTable programmatically from a Class on a JForm and adding DefaultTableModel in my JTable for holding data then adding rows one by one in DefaultTableModel as follows.

private JTable desiredJTable = new JTable();
private DefaultTableModel tableModel = new DefaultTableModel();
private List<String> myArrayOne= new ArrayList<String>();
private List<String> myArrayTwo= new ArrayList<String>();
private Map<String, Integer> myDictionaryOne= new HashMap<String, Integer>();
private Map<String, Integer> myDictionaryTwo= new HashMap<String, Integer>();

And I am adding rows like below so I dont know about the fix length of single color rows.

int RowIndex = 0;
int i = 0;
for (String word : myDictionaryOne.keySet())
{
    if (myArrayOne.contains(word) == true)
    {
        tableModel.addRow(new Object[] { word });
        //tableModel.setRowColour(RowIndex, Color.GREEN);                        
        RowIndex++;
        i++;
    }
    if (i >= 10)
    {
        break;
    }
} 

int i = 0;
for (String word : myDictionaryTwo.keySet())
{
    if (myArrayTwo.contains(word) == true)
    {
        tableModel.addRow(new Object[] { word });
        //tableModel.setRowColour(RowIndex, Color.RED);                        
        RowIndex++;
        i++;
    }
    if (i >= 10)
    {
        break;
    }
} 

I want to change color where I added the commented code so How can I do this? I have an ideas to make a class where I will save these rows no with there desired color and later in the End, just render the whole table at once? Anything is possible to do this?

Updated:

I used the below code but its working nearly as per my desire but its not showing the right color in the rows as per saved in the ArrayList...

CustomRenderer colouringTable = new CustomRenderer();
int RowIndex = 0;
int i = 0;
for (String word : myDictionaryOne.keySet())
{
    if (myArrayOne.contains(word) == true)
    {
        tableModel.addRow(new Object[] { word });
        //tableModel.setRowColour(RowIndex, Color.GREEN);
        colouringTable.setColors(Color.GREEN);                           
        RowIndex++;
        i++;
    }
    if (i >= 10)
    {
        break;
    }
} 

int i = 0;
for (String word : myDictionaryTwo.keySet())
{
    if (myArrayTwo.contains(word) == true)
    {
        tableModel.addRow(new Object[] { word });
        //tableModel.setRowColour(RowIndex, Color.RED);
        colouringTable.setColors(Color.RED);                         
        RowIndex++;
        i++;
    }
    if (i >= 10)
    {
        break;
    }
} 
desiredJTable.getColumnModel().getColumn(0).setCellRenderer(colouringTable);

And added a class...

// JTable Colouring Class
class CustomRenderer extends DefaultTableCellRenderer 
{
    private List<Color> desiredColors = new ArrayList<Color>();
    private static final long serialVersionUID = 6703872492730589499L;

    public void setColors(Color incomingColor)
    {
        desiredColors.add(incomingColor);
    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        // This Code Is Not Working Perfectly | Its Colouring All With Same Last Color...
        for (int i = 0; i < desiredColors.size(); i++) {
            cellComponent.setBackground(desiredColors.get(i));
        }
        /*
        // This Code Is Working
        if(row == 0){
            cellComponent.setBackground(Color.YELLOW);
        } else if ( row == 1){
            cellComponent.setBackground(Color.GRAY);
        } else {
            cellComponent.setBackground(Color.CYAN);
        }
        */
        return cellComponent;
    }
}

So How to fix this now...???

  • 1
    did you see here: http://stackoverflow.com/questions/15071668/cell-renderer-for-jtable-coloured-rows – Azodious Jan 02 '17 at 11:57
  • That is also near to me but How I can make this `CustomRenderer` class dynamic means to change color of desired random row only. Thats the main problem. I am still trying many other codes and welcome your suggestion and CODES also... :D – Sahar Jabeen Jan 02 '17 at 12:17
  • You're confused as you're trying to change the background color from the model, and the model is all about the data and has nothing to do with the view -- including the setting of background color. The way to do this is via the view's renderer, pure and simple. This is well explained in the JTable tutorials and in the many answers on this site that explain how to use table cell renderers. – Hovercraft Full Of Eels Jan 02 '17 at 12:38
  • The renderer can make the test you are making in the above code, or the above code can set a flag in the rendered object and the renderer can test that. The reason the renderer is the place to do this is, in general, values in the table can change, and if your test value were to change you'd likely want the color to change. So after a value fires, the table is rendered again, the renderer called, and it tests the value there instead of having to test it all the places where it might change. – arcy Jan 02 '17 at 12:43
  • So as per your suggestions, I am now here. Check out my updated question... – Sahar Jabeen Jan 02 '17 at 12:45
  • I've outlined an approach below. If you have trouble, please edit your question to include a [mcve] that shows your revised approach. – trashgod Jan 02 '17 at 12:46
  • I tried again to show my approach and make the question clear. I am checking your answer too... – Sahar Jabeen Jan 02 '17 at 12:57
  • Thanks you guys for helping me with logic and ideas... – Sahar Jabeen Jan 02 '17 at 13:03

2 Answers2

2

Your TableModel should store the information needed to determine the cell's color when the renderer is called for that cell. In this complete example, each Row has a state, and the custom TableCellRenderer queries that state to determine the color to display. This related example illustrates how to create a custom TableModel using a Map.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • What about my UPDATED question. I am nearly near to my target there... I am also checking your links. Thanks in advance... – Sahar Jabeen Jan 02 '17 at 12:48
  • The approach you've outlined [here](http://stackoverflow.com/a/41427370/230513) separates the model and view well enough; you may find a custom `TableModel` more scalable as your application evolves. – trashgod Jan 02 '17 at 16:33
2

Finally I am able to do what I want with the help of other guys. I used the below code and its working as per my desire and showing the right color in the rows as per saved in the ArrayList...

CustomRenderer colouringTable = new CustomRenderer();
int RowIndex = 0;
int i = 0;
for (String word : myDictionaryOne.keySet())
{
    if (myArrayOne.contains(word) == true)
    {
        tableModel.addRow(new Object[] { word });
        colouringTable.setColors(Color.GREEN);                           
        RowIndex++;
        i++;
    }
    if (i >= 10)
    {
        break;
    }
} 

int i = 0;
for (String word : myDictionaryTwo.keySet())
{
    if (myArrayTwo.contains(word) == true)
    {
        tableModel.addRow(new Object[] { word });
        colouringTable.setColors(Color.RED);                         
        RowIndex++;
        i++;
    }
    if (i >= 10)
    {
        break;
    }
} 
desiredJTable.getColumnModel().getColumn(0).setCellRenderer(colouringTable);

And added a class...

// JTable Colouring Class
class CustomRenderer extends DefaultTableCellRenderer 
{
    private List<Color> desiredColors = new ArrayList<Color>();

    public void setColors(Color incomingColor)
    {
        desiredColors.add(incomingColor);
    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        for (int i = 0; i < desiredColors.size(); i++) {
            if(row == i){
                cellComponent.setBackground(desiredColors.get(i));
            }
        }
        return cellComponent;
    }
}

Thanks for reading... :-)