我读了这个问题
Programmatically select multiple cells in a JTable这个帖子http://www.java2s.com/Tutorial/Java/0240__Swing/Selectacellcell21.htm
和此帖子http://esus.com/programmatically-selecting-a-jtable-cell/
采用代码
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//table.setRowSelectionInterval(0, 2);
//table.setColumnSelectionInterval(0, 1);
table.setRowSelectionAllowed(false);
table.setColumnSelectionAllowed(false);
table.changeSelection(0, 0, true, false);
table.changeSelection(2, 2, true, false);
我想这样做,但是只使用代码,没有点击(对于我使用的图片点击)!
如何仅使用代码(不单击)选择JTable的非连续单元格?
编辑Programmatically select multiple cells in a JTable的答案
在列表中填写要点。
List<Point> selected = new ArrayList<>(Arrays.asList(new Point(0, 0), new Point(2, 2)));
这里是代码。
public class TableSelection extends JFrame {
private static final long serialVersionUID = 1L;
String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
Object[][] data = {{"Kathy", "Smith", "Snowboarding", Integer.valueOf(5), Boolean.valueOf(false)},
{"John", "Doe", "Rowing", Integer.valueOf(3), Boolean.valueOf(true)},
{"Sue", "Black", "Knitting", Integer.valueOf(2), Boolean.valueOf(false)},
{"Jane", "White", "Speed reading", Integer.valueOf(20), Boolean.valueOf(true)},
{"Joe", "Brown", "Pool", Integer.valueOf(10), Boolean.valueOf(false)}};
public TableSelection() {
JPanel main = new JPanel();
JTable table = new JTable(data, columnNames) {
private static final long serialVersionUID = 1L;
List<Point> selected = new ArrayList<>(Arrays.asList(new Point(0, 0), new Point(2, 2)));
@Override
protected void processMouseEvent(MouseEvent e) {
if (e.getID() != MouseEvent.MOUSE_PRESSED) {
return;
}
int row = ((JTable) e.getSource()).rowAtPoint(e.getPoint());
int col = ((JTable) e.getSource()).columnAtPoint(e.getPoint());
if (row >= 0 && col >= 0) {
Point p = new Point(row, col);
if (selected.contains(p)) {
selected.remove(p);
} else {
selected.add(p);
}
}
((JTable) e.getSource()).repaint();
}
@Override
public boolean isCellSelected(int arg0, int arg1) {
return selected.contains(new Point(arg0, arg1));
}
};
JScrollPane pane = new JScrollPane(table);
main.add(pane);
this.add(main);
this.setSize(800, 600);
this.setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new TableSelection();
}
}