我建议使用 CTRL 代替 ALT 进行多选。一方面,任何想要多选的用户都已经知道怎么做,因为 CTRL 是多选事实上的标准修饰键。其次,您可以免费获得您想要的行为,而无需实现任何特殊的东西(也许除了您喜欢的配色方案)。
package com.example.table.multiselect;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class MultiRowTableSelect extends JFrame {
public MultiRowTableSelect() {
DefaultTableModel model = new DefaultTableModel(0, 3);
model.addRow(new Integer[]{1, 2, 3});
model.addRow(new Integer[]{4, 5, 6});
model.addRow(new Integer[]{7, 8, 9});
model.addRow(new Integer[]{10, 11, 12});
JTable tbl = new JTable(model);
tbl.setRowSelectionAllowed(true); // when you click a cell, the entire row will be highlighted
/* Assuming you want all cells to be rendered using the custom renderer
* unless otherwise overridden, you can simply set the JTable's default
* renderer. The implementation is so simple here that I'm just
* creating an anonymous subclass of DefaultTableCellRenderer.
*/
tbl.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (isSelected) {
c.setForeground(Color.RED); // you can set the foreground and/or background here
}
return c;
}
});
add(new JScrollPane(tbl), BorderLayout.CENTER);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
pack();
setSize(400, 200);
setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
new MultiRowTableSelect();
}
}