PDA

View Full Version : چگونه می توان در Jtable با استفاده از CellRender رنگ ردیف ها را تغییر داد ?



!ManeMohandes
شنبه 31 اردیبهشت 1390, 14:41 عصر
سلام
من یک جدول jtable دارم که می خواهم هنگام اجرای برنامه یکی در میان رنگ ردیف های آن را تغییر دهم کسی می تونه بهم بگه چه طوری؟ تو نت گشتم دیدم باید از CellRender استفاده کنم ولی درست کار نکرد، کسی میدونه چه طور باهاش کار کنم؟

پیشاپیش ممنونم

ermia2008
دوشنبه 02 خرداد 1390, 08:06 صبح
سلام
به این کد یه نگاه بندازید:



class ColorRenderer extends JLabel implements TableCellRenderer {

public ColorRenderer() {
setOpaque(true);
}

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

if (value != null) {
setText(value.toString());
}
if (isSelected) {
setBackground(table.getSelectionBackground());
setForeground(table.getSelectionForeground());
} else {
setBackground(table.getBackground());
setForeground(table.getForeground());

if (row % 2 == 0) {
setBackground(java.awt.Color.GRAY);
}
}
return this;
}
}

public class TableRowColor extends JFrame {

public TableRowColor() {
JTable table = new JTable(new DefaultTableModel(new Object[][]{
{"1", "2", "3", "4"},
{"2", "3", "4", "5"},
{"3", "4", "5", "6"},
{"4", "5", "6", "7"}},
new Object[]{"A", "B", "C", "D"}));

ColorRenderer cr = new ColorRenderer();

for (int i = 0; i < table.getColumnCount(); i++) {
table.getColumn(table.getColumnName(i)).setCellRen derer(cr);
}
JScrollPane scroll = new JScrollPane(table);
this.setContentPane(scroll);
this.setBounds(100, 50, 300, 150);
}

public static void main(String arg[]) {
TableRowColor test = new TableRowColor();
test.setVisible(true);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
}
}