关闭

Swing —— JTable鼠标移入更换单元格颜色

标签: SwingJTable
1186人阅读 评论(0) 收藏 举报
分类:

效果图



相关代码 展开详细说明

public class MouseHoverTable extends JFrame {
	Color color = new Color(232, 232, 232);
	JTable table;
	int row = 0;                    // 记录鼠标所移动到的行
	int column = 0;                    // 记录鼠标所移动到的列
	MouseHoverTable() {
		super("鼠标悬浮时更换颜色");
		table = new JTable(10, 10);
		// 单元格边框颜色
		table.setGridColor(color);
		// 行高与列宽
		table.setRowHeight(50);
		TableColumnModel columnModel = table.getColumnModel();
		int columnCount = columnModel.getColumnCount();
		for (int i = 0; i < columnCount; i++) {
			TableColumn col = columnModel.getColumn(i);
			col.setMinWidth(50);
			col.setMaxWidth(50);
		}
 
	// 添加鼠标移动监听, 以及设置列渲染器
	CellRendererAndMouseListener rendererAndListener = new CellRendererAndMouseListener();
	table.addMouseMotionListener(rendererAndListener);
	table.setDefaultRenderer(Object.class, rendererAndListener);
	// 添加到内容
	this.getContentPane().add(table);
	}
 
	public static void main(String[] args) {
		JFrame frame = new MouseHoverTable();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}
 
	public class CellRendererAndMouseListener extends JLabel implements
		TableCellRenderer, MouseMotionListener {
 
	public CellRendererAndMouseListener() {
		setOpaque(true);
	}
 
	public Component getTableCellRendererComponent(JTable table,
		Object value, boolean isSelected, boolean hasFocus, int row,
		int column) {
		if (MouseHoverTable.this.row == row && 
			MouseHoverTable.this.column == column) {
			this.setBackground(color);
		} else {
			this.setBackground(Color.WHITE);
		}
		return this;
	}
	public void mouseMoved(MouseEvent e) {
		JTable table = (JTable) e.getSource();
		row = table.rowAtPoint(e.getPoint());
		column = table.columnAtPoint(e.getPoint());
		table.repaint();
	}
 
	public void mouseDragged(MouseEvent e) {}
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:119108次
    • 积分:2700
    • 等级:
    • 排名:第13412名
    • 原创:61篇
    • 转载:1篇
    • 译文:1篇
    • 评论:16条
    文章分类
    最新评论