我的问题是这是否是在 JTable 中定位数据的一种方法。
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
{"Peter", new Integer(15)},
{"Max", new Integer(12)},
},
new String[] {
"Name", "Age"
}
)
现在我想要例如的位置。 12 这样当我点击按钮时我就可以标记它。如果可能的话,如果我还可以搜索号码或名称,那就太好了。
提前感谢您的回答
最佳答案
这里是查找任意列中包含指定值的第一行的方法。
public static int firstRowContainsObject(JTable table, Object obj) {
for (int i = 0; i < table.getRowCount(); i++) {
for (int j = 0; j < table.getColumnCount(); j++) {
if (Objects.equals(obj, table.getValueAt(i, j))) {
return i;
}
}
}
return -1;
}
注意:如果在表中没有找到这样的对象,此方法返回 -1。
在您的案例中的用法:
firstRowContainsObject(table, 12); // returns 1
firstRowContainsObject(table, "Peter"); // returns 0
firstRowContainsObject(table, "Mary"); // returns -1
关于java - 获取数据在 JTable 中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48168929/