在JTable中添加组件后,当我们选中某一行时,我们会发现其他栏的背景色会变为table设置的选中背景色,而带有组件的那一栏背景色却不变
这时,我们需要在TableCellRenderer中添加一个填充方法
下面以JLable组件为例:
import java.awt.Component;
import java.awt.Image;
import java.net.URL;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
public class MyLabelRenderer extends JLabel implements TableCellRenderer{
public void fillColor(JTable t,JLabel l,boolean isSelected ){
if(isSelected){
l.setBackground(t.getSelectionBackground());
l.setForeground(t.getSelectionForeground());
}
else{ //如果想让组件不使用table中的前景色,背景色,把else这段去掉就好了.然后在下面getTableCellRendererComponent()函数中定义自己想要的组件样式
l.setBackground(t.getBackground());
l.setForeground(t.getForeground());
}
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
// TODO Auto-generated method stub
URL url=MyButtonRenderer.class.getResource(value+".png");
ImageIcon icon=new ImageIcon(url);
icon.setImage(icon.getImage().getScaledInstance(22, 22, Image.SCALE_DEFAULT));
setIcon(icon);
setText(value.toString());
setBorder(BorderFactory.createEmptyBorder(3,10,3,10));
setOpaque(true);//组件要设置为不透明
fillColor(table,this,isSelected);//调用填充方法
return this;
}
}
对了,如果组件为进度条JProgressBar,并且设置了进度条颜色时,别忘了把fillColor()中的l.setForeground(t.getSelectionForeground());去掉
JTable的默认选中前景色(SelectionForeground)为黑色
附张截图: