14. 58. 2. 会变的行高 Creating a JTable with rows of variable height


14. 58. 2. 会变的行高 Creating a JTable with rows of variable height_第1张图片

import java.awt.Component;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;


public class VariableHeightTable {

	public static void main(String[] args) {
		JFrame f = new JFrame("会变的行高");
		StringTableModel imageTableModel = new StringTableModel();
		JTable imageTable = new JTable(imageTableModel);
		imageTable.getColumnModel().getColumn(0).setCellRenderer(new VariableHeightRenderer());
		f.getContentPane().add(new JScrollPane(imageTable));
		f.pack();
		f.setVisible(true);
	}
}

//一个单元格渲染器,注意,这是个标签
class VariableHeightRenderer extends JLabel implements TableCellRenderer{
	public VariableHeightRenderer(){
		super();//父类方法
		setOpaque(true);//设置透明
		setHorizontalAlignment(JLabel.CENTER);//设置横向中心
	}
	
	/*
	 * 返回用于绘制单元格的组件。此方法用于在绘制前适当地配置渲染器。 
	 * table:要求渲染器绘制的 JTable;可以为 null
	 * value:要呈现的单元格的值。由具体的渲染器解释和绘制该值。
	 * 			例如,如果 value 是字符串 "true",则它可呈现为字符串,或者也可呈现为已选中的复选框。null 是有效值
	 * isSelected - 如果使用选中样式的高亮显示来呈现该单元格,则为 true;否则为 false
	 * hasFocus - 如果为 true,则适当地呈现单元格。例如,在单元格上放入特殊的边框,如果可以编辑该单元格,
	 * 			则以彩色呈现它,用于指示正在进行编辑
	 * row - 要绘制的单元格的行索引。绘制头时,row 值是 -1
	 * column - 要绘制的单元格的列索引
	 */
	public Component getTableCellRendererComponent(JTable table, Object value,
			boolean isSelected, boolean hasFocus, int row, int column) {
		if(isSelected){
			setBackground(UIManager.getColor("Table.selectionBackground"));
		}
		if(hasFocus){//返回一个边框
			setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
			if(table.isCellEditable(row, column)){
				super.setForeground(UIManager.getColor("Table.focusCellForeground"));
				super.setBackground(UIManager.getColor("Table.focusCellBackground"));
			}
		}else{//上左下右都为1的边框
			setBorder(BorderFactory.createEmptyBorder(100,1,1,1));
		}
		setText((String)(value));
		table.setRowHeight(row,getPreferredSize().height + row * 10);
		return this;
	}
}

//一个抽象的TableModel
class StringTableModel extends AbstractTableModel{
	public static final int IMG_COL = 0;//一个不变的列
	public String[] m_colNames = {"Variable Dimension","会变的尺寸"};//string数组
	public Class[] m_colTypes = {String.class};
	
	public StringTableModel(){//空构造
		super();
	}

	public int getColumnCount() {//获得列数量
		return m_colNames.length;
	}

	public int getRowCount() {//获得行数量
		return 3;
	}

	public String getColumnName(int col){//获得列名
		return "第" + col + "列";
	}
	
	public Object getValueAt(int arg0, int arg1) {//拿到单元格的值
		return "会变的行高";
	}
	
}



你可能感兴趣的:(14. 58. 2. 会变的行高 Creating a JTable with rows of variable height)