我有一个表格(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"& "World "打印: HelloWorld
Selecting all rows prints: HelloStackOverflow