自定義渲染類:
public class RenderByCondition extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
//如果年齡在36歲以上的人的名字高亮顯示
Component comm=super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
String strage=table.getValueAt(row, 3).toString();
String strai=table.getValueAt(row, 2).toString();
int age=Integer.parseInt(strage);
comm.setBackground(Color.white);
//如果年齡大於36,且愛好足球的人的名字高亮顯示
if((age>=36&&"足球".equals(strai))&&column==0){
comm.setBackground(Color.RED);
}
return comm;
}
}
渲染的類:
public class Table1 extends JFrame{
private JTable jTable;
private JScrollPane jsp;
private String[][] rows = { { "li1", "男", "手球", "25", "chos" },
{ "li2", "男", "乒乓球", "26", "chos3" }, { "li3", "男", "足球", "44", "chos4" },
{ "li34", "男", "籃球", "36", "chos5" } };
private String[] columns = { "姓名", "性別", "愛好", "年齡", "小三" };
public Table1(){
createJtable();
jsp=new JScrollPane(jTable);
add(jsp,BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocation(400, 200);
this.setSize(400, 600);
// jTable.setDefaultRenderer(Object.class, new TableRender());
jTable.setDefaultRenderer(Object.class, new RenderByCondition());
setVisible(true);
}
public JTable createJtable() {
jTable = new JTable(rows,columns);
return null;
}
public static void main(String[] args) {
Table1 table1= new Table1();
}
}
這是一個以表格中其他行數據爲條件,讓第一行高亮顯示的例子。工作中用到了,雖然說比較簡單,但是我費了好大的勁,所以將它寫下來。