我有一个表(1 列,多行),其中包含书籍名称列表和一个按钮。 什么是正确的选择监听器,以便如果我选择表上的多个行,当我按下按钮时,它会将所选行的值以串联格式分配给变量?
例如,如果我从表中选择项目 1 到 7,它将被分配给变量,如下所示:
String selectedBooks = item1 + item2 + item3...;
我稍后将使用 selectedBooks
的值进行 sqlite 查询。
感谢您的帮助
最佳答案
使用table.getSelectedRows()
将返回所选行的索引。然后使用 table.getValueAt(row,column)
方法从特定单元格获取值。
一个小例子:
public class SelectedRowExample extends JFrame {
public SelectedRowExample() {
super("");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Column");
model.addRow(new Object[] { "Hello" });
model.addRow(new Object[] { "Stack" });
model.addRow(new Object[] { "Overflow" });
JTable table = new JTable(model);
table.getSelectionModel().addListSelectionListener(e -> {
if (e.getValueIsAdjusting()) {
StringBuilder sb = new StringBuilder();
for (int row : table.getSelectedRows()) {
sb.append(table.getValueAt(row, 0));
}
System.out.println(sb.toString());
}
});
setLayout(new BorderLayout());
add(table);
setLocationByPlatform(true);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new SelectedRowExample().setVisible(true));
}
}
选择“Hello”打印:Hello
选择“Hello”和“World”打印:HelloWorld
选择所有行打印:HelloStackOverflow
关于java - 如何从 JTable 的多行中获取值并将其分配给变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61406113/