当前位置: 技术问答>java相关
怎么在jtable中用颜色分隔每一行?
来源: 互联网 发布时间:2015-11-05
本文导语: 不如一行有颜色一行没有颜色。 | public class MyTableRenderer extends DefaultTableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,boolea...
不如一行有颜色一行没有颜色。
|
public class MyTableRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected,boolean cellHasFocus,
int row,int col) {
if(row==1)
setBackground(Color.red);
setText((value == null) ? "" : value.toString());
return this;
}
}
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected,boolean cellHasFocus,
int row,int col) {
if(row==1)
setBackground(Color.red);
setText((value == null) ? "" : value.toString());
return this;
}
}
|
class ColorRenderer extends DefaultTableCellRenderer {
public ColorRenderer() {
super();
//setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
}
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(isSelected){
comp.setForeground(table.getSelectionForeground());
comp.setBackground(table.getSelectionBackground());
}
else if (row % 2 == 0) {
comp.setForeground(table.getForeground());
comp.setBackground(Color.yellow);
} else {
comp.setForeground(table.getForeground());
comp.setBackground(Color.green);
}
setText(value.toString());
return comp;
}
}
table.setDefaultRenderer(Object.class, new ColorRenderer());
public ColorRenderer() {
super();
//setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
}
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(isSelected){
comp.setForeground(table.getSelectionForeground());
comp.setBackground(table.getSelectionBackground());
}
else if (row % 2 == 0) {
comp.setForeground(table.getForeground());
comp.setBackground(Color.yellow);
} else {
comp.setForeground(table.getForeground());
comp.setBackground(Color.green);
}
setText(value.toString());
return comp;
}
}
table.setDefaultRenderer(Object.class, new ColorRenderer());