import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class TableDemo
{
public static void main(String[] args)
{
final JFrame frame=new JFrame("Table Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyTable table=new MyTable();
table.setPreferredSize(new Dimension(400, 600));
frame.add(new JScrollPane(table));
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
class MyTable extends JTable
{
private static final long serialVersionUID = 1L;
private DefaultTableModel model=new DefaultTableModel();
public MyTable() {
model.addColumn("Alpha");
model.addColumn("Beta");
model.addColumn("Gamma");
for(int i=0;i<20;i++) {
model.addRow(new Object[] {"a","b","c"});
}
setModel(model);
TableCellRenderer renderer=new MyTableRenderer();
getColumn("Alpha").setCellRenderer(renderer);
getColumn("Beta").setCellRenderer(renderer);
getColumn("Gamma").setCellRenderer(renderer);
}
public boolean isRowEditable(int row)
{
return row== 1 ? true : false;
}
@Override
public boolean isCellEditable(int row, int column)
{
return isRowEditable(row);
}
}
class MyTableRenderer extends DefaultTableCellRenderer
{
private static final long serialVersionUID = 1L;
Color def;
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component comp=super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(def==null)
def=comp.getBackground();
if(table instanceof MyTable) {
if(((MyTable)table).isRowEditable(row))
comp.setBackground(def);
else
comp.setBackground(Color.GRAY);
}
return comp;
}
}