获取所有选中的复选框索引 [英] Get all selected index of Checkbox
问题描述
我是 Java Swing 的初学者.我有一个 3 列的表.第一列只有复选框.我想获取复选框的所有选定项的索引并将其存储在 ArrayList
中.我怎样才能做到这一点?
I am a beginner to Java Swing. I have a table with 3 columns. The first column has only check boxes. I wanted to get the index of all the selected items of the check box and store it in an ArrayList
. How can I accomplish this?
推荐答案
当您使用 JTable 时,您正在为复选框列"使用 TableCellRenderer.只要将复选框添加到第 1 列,您就知道"复选框是在哪一行创建的.正如您所知道的 row(=index) ,您可以注册一个操作来收集复选框索引.
As you use a JTable you are using a TableCellRenderer for the "checkbox column". As long you add check boxes to column 1 you "know" in which row the checkbox is created. As you know the row(=index) you can register an action to collect together the checked boxes index.
(从头开始)
public class MyRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, final int row, int column) {
if (column != 1) {
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
JCheckBox cb = new JCheckBox();
cb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
list.add(row); // whatever list is ...
}
});
return cb;
}
}
这篇关于获取所有选中的复选框索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!