我也有类似的情况。我的解决方案(抱歉,不想编写一个庞大的类)是为所有列添加一个 Cell Renderer,它是表的鼠标侦听器。由于渲染器知道选择了哪些按钮,它可以以不同的方式渲染它们。
public class MultipleSelectionRenderer extends DefaultTableCellRenderer implements MouseListener {
private JTable table;
private Map<String, Boolean> selectedMap = new LinkedHashMap<String, Boolean>();
TableUpdateIfc updater;
public MultipleSelectionRenderer(TableUpdateIfc updater, JTable table, Map<String, Boolean> selectedMap) {
this.table = table;
this.selectedMap = selectedMap;
this.updater = updater;
}
@Override
public void mouseReleased(MouseEvent e) {
if(e.getSource() == table){
try {
if(!e.isControlDown())
selectedMap.clear();
selectedMap.put(table.getSelectedRow()+":"+table.getSelectedColumn(), true);
} catch (Exception ex) {
selectedMap.clear();
}
}
updater.updateMultipleSelectionTable(table);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) { }
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
/**
*
* @param table
* @param value
* @param isSelected
* @param hasFocus
* @param row
* @param column
* @return
*/
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component result =super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(selectedMap.get(row+":"+column) != null && selectedMap.get(row+":"+column) == true) {
setText(getHTMLString(value));
}
return result;
}
private String getHTMLString(Object value){
String html = "<html><body><table cellpadding=0><tr>";
html = html + "<td bgcolor=#bf65a5>";
html = html + value.toString();
html = html + "</td><td> " + value+"</td>";
html = html + "</tr></table></body></html>";
return html;
}
}