`
tuxq5721
  • 浏览: 33315 次
社区版块
存档分类
最新评论

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

阅读更多

效果图

 

相关代码 展开详细说明

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) {}
	}
}



 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics