自定义JTable中的单元格背景

自定义JTable中的单元格背景,需重写它的渲染器。

 

代码如下:

 

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;


public class JTableDemo extends JPanel{

	private JTable table;
	private DefaultTableModel tableModel;
	private Vector<String> rowItem;
	private String [] col = {"Col1","Col2","Col3","Col4","Col5","Col6"};
	public JTableDemo(){
		initPanel();
		this.setVisible(true);
	}
	
	private void initPanel() {
		this.setLayout(new BorderLayout());
		tableModel = new DefaultTableModel();
		tableModel.setColumnIdentifiers(col);
		rowItem = new Vector();
		for(int i = 0;i<col.length; i++){
			rowItem.add("aaa");
		}
		for(int i=0; i<10; i++){
			tableModel.addRow(rowItem);
		}
		table = new JTable(tableModel);
		table.setRowHeight(30);
		table.setDefaultRenderer(Object.class, new MyTableCellRenderer());
		table.setIntercellSpacing(new Dimension(0,0));
		this.add(table.getTableHeader(),BorderLayout.NORTH);
		this.add(table, BorderLayout.CENTER);
	}

	public static void main(String [] args){
		JFrame f = new JFrame("JTableDemo");
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setSize(800, 600);		
		f.add(new JTableDemo());
//		f.pack();
		f.setVisible(true);
	}
}

 

重写的渲染器代码:

 

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;


public class MyTableCellRenderer extends DefaultTableCellRenderer {

	@Override
	public Component getTableCellRendererComponent(JTable table, Object value,
			boolean isSelected, boolean hasFocus, int row, int column) {
		// TODO Auto-generated method stub
		JComponent c = (JComponent) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
		JTableHeader head = table.getTableHeader();
		if(head!=null){
			head.setBackground(Color.gray);
			head.setForeground(Color.white);
			head.setPreferredSize(new Dimension(300,40));
		}
		if(column%2==1){			
			if(row%2==1){
				c.setBackground(Color.LIGHT_GRAY);
			}else{
				c.setBackground(Color.DARK_GRAY);
			}
		}else{
			if(row%2==0){
				c.setBackground(Color.LIGHT_GRAY);
			}else{
				c.setBackground(Color.DARK_GRAY);
			}
		}
		
		return this;
	}
	
}

 

 

你可能感兴趣的:(java,C++,c,swing,C#)