Coloring JTable row dynamicaly, row selection issue on moving row

I am facing some issue with JTable.

I am doing is: moving table rows dynamically and changing color of rows dynamically. I am facing some following issues:

  1. With moving rows, row selection is not moving. So, problem is, user will select row and do something, meanwhile rows will move and selected row will be other, and user operation is getting performed on other row than desired row.
  2. Some time only part row (few columns) getting changed color, some time whole row is getting colored.

So, I want whole row to be colored dynamically, and row selection should move with row moves.

Somehow I managed to update color of whole row,

but still I have issue of row selection.

Below is code:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.util.Vector;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

public class NewClass extends JFrame {

    private JTable table;
    private JScrollPane scrollPane;
    private DefaultTableModel defaultTableModel;

    public NewClass() {
        setLocationByPlatform(true);
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(1000, 700));
        setTitle("Table Issues");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        createTableModel();
        createTable();
        table.setModel(defaultTableModel);

        scrollPane = new JScrollPane(table);

        getContentPane().add(scrollPane, BorderLayout.CENTER);

        pack();
    }

    private void createTable() {
        table = new JTable() {

            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component comp = super.prepareRenderer(renderer, row, column);
                JComponent jc = (JComponent) comp;
                if (!isRowSelected(row)) {
                    int modelRow = convertRowIndexToModel(row);
                    int i = Integer.parseInt((String) getModel().getValueAt(modelRow, 2));
                    if (i == 0) {
                        jc.setBackground(Color.orange);
                    } else if (i == 1 || i == 2) {
                        jc.setBackground(Color.yellow);
                    } else if (i == 3) {
                        jc.setBackground(Color.green);
                    } else {
                        jc.setBackground(Color.white);
                    }
                }
                return comp;
            }
        };
    }

    private void createTableModel() {
        Vector cols = new Vector();
        cols.add("1");
        cols.add("2");
        cols.add("3");
        cols.add("4");
        cols.add("5");

        Vector rows = new Vector();

        for (int i = 0; i < 50; i++) {
            Vector row = new Vector();
            row.add((i + 1) + "");
            row.add("B");
            int r = (int) (Math.random() * 5);
            row.add(r + "");
            row.add("D");
            row.add("E");
            rows.add(row);
        }

        defaultTableModel = new DefaultTableModel(rows, cols) {

            Class[] types = new Class[]{
                String.class, String.class, String.class, String.class, String.class
            };

            @Override
            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(new NimbusLookAndFeel());
        } catch (Exception e) {
        }

        final Object lock = new Object();
        final NewClass nc = new NewClass();
        nc.setVisible(true);

        new Thread(new Runnable() {

            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                    }
                    synchronized (lock) {
                        int i = (int) (Math.random() * 5);
                        int row = (int) (Math.random() * 50);
                        int move = (int) (Math.random() * 50);

                        nc.defaultTableModel.setValueAt(i + "", row, 2);
                        nc.defaultTableModel.moveRow(row, row, move);
                        nc.defaultTableModel.setValueAt(i + "", row, 2);
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {

            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                    }
                    synchronized (lock) {
                        int i = (int) (Math.random() * 5);
                        int row = (int) (Math.random() * 50);
                        int move = (int) (Math.random() * 50);

                        nc.defaultTableModel.setValueAt(i + "", row, 2);
                        nc.defaultTableModel.moveRow(row, row, move);
                        nc.defaultTableModel.setValueAt(i + "", row, 2);
                    }
                }
            }
        }).start();

        while (true) {
            synchronized (lock) {
                int i = (int) (Math.random() * 5);
                int row = (int) (Math.random() * 50);
                int move = (int) (Math.random() * 50);

                nc.defaultTableModel.setValueAt(i + "", row, 2);
                nc.defaultTableModel.moveRow(row, row, move);
                nc.defaultTableModel.setValueAt(i + "", row, 2);
                if (i % 2 == 1) {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
}

In this code, when you select row, after movements in rows, selected row will be other, i.e. row selection is not moving with row moves.

Please help me on this.

Answers


I resolved issue of coloring rows, by overridding setValueAt method of DefaultTableModel. Overridden method is:

@Override
public void setValueAt(Object aValue, int row, int column) {
    Vector rowVector = (Vector)dataVector.elementAt(row);
    rowVector.setElementAt(aValue, column);
    // update whole row instead of single cell
    fireTableRowsUpdated(row, row);
}

The issue may be due to multiple threads doing heavily work, and EDT may not be getting time to update whole row. With setting value by setValueAt method of DefaultTableModel, that column was coloring for sure due to fire of cell update event.

But still I have issue of selection not moving with row moves in table.

Opening new thread for row selection issue.


Need Your Help

I couldn't access VIOS from browser after installing

ibm aix

I have installed a VIOS using nimol, install completed successfully but I could access the VIOS from browser.

Store/Sync Facebook Graph in a NoSQL (MongoDB)

facebook mongodb graph nosql

I'm building an app that needs to be able to extend facebook graph data.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.