Questo codice copiato da internet e da mè riadattato alla bene in meglio (dalle mie non complete conoscenze di java.. ) sembrerebbe colorare le righe a seconda del contenuto di una cella, è già qualcosa ma vorrei arrivare a colorare le singole celle(row,column)
import java.awt.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.table.*;
public class TablePrepareRenderer extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
private String tableFlag = "";
public TablePrepareRenderer() {
Object[] columnNames = {"Field1", "Field2", "Flag"};
Object[][] data =
{
{"1", "2", "A"},
{"1", "2", "A"},
{"1", "2", "F"},
{"1", "2", "R"},
{"1", "2", "R"},
{"1", "2", "C"},
{"1", "2", "T"},
{"1", "2", "X"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
private static final long serialVersionUID = 1L;
@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
table = new JTable(model)
{
private static final long serialVersionUID = 1L;
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
{
Component c = super.prepareRenderer(renderer, row, column);
if (!isRowSelected(row)) {
if (table.getColumnCount() >= 0) {
tableFlag = (String) table.getValueAt(row, 2);
if ((tableFlag != null) &&
(!tableFlag.isEmpty()))
{
c.setFont(new Font("Serif", Font.BOLD, 12));
c.setBackground(Color.RED);
switch(tableFlag)
{
case "A":
c.setBackground(Color.LIGHT_GRAY);
break;
case "T":
c.setBackground(Color.LIGHT_GRAY);
break;
case "F":
c.setBackground(Color.blue);
break;
case "R":
c.setBackground(Color.GREEN);
break;
case "C":
c.setBackground(Color.GREEN);
break;
}
}
}
}
if (isRowSelected(row) && isColumnSelected(column)) {
((JComponent) c).setBorder(new LineBorder(Color.red));
}
return c;
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TablePrepareRenderer frame = new TablePrepareRenderer();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
Medito anche l'abbandono di jtable a favore di un'array di textfield