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

时间:2023-01-27 10:07:08

效果图

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