gpt4 book ai didi

java - JTable通过代码选择不连续的单元格

转载 作者:行者123 更新时间:2023-12-02 09:23:35 27 4
gpt4 key购买 nike

我读了这个问题

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);


但是我有: enter image description here

我想这样做,但是只使用代码,没有点击(对于我使用点击的图像)!

enter image description here

如何仅使用代码(不单击)选择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();
}

}

关于java - JTable通过代码选择不连续的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58496313/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com