我认为您正在尝试以编程方式选择JTable
.
这JTable
只是一个显示机制。不是在表(视图)中选择行,而是在 中选择行SelectionModel
,所以看看我做的这个小例子:
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Test extends JFrame {
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Test().createAndShowUI();
}
});
}
private void createAndShowUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents(frame);
frame.pack();
frame.setVisible(true);
}
private void initComponents(JFrame frame) {
String data[][] = {
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"},
{"10", "11", "12"}
};
String col[] = {"Col 1", "Col 2", "Col 3"};
DefaultTableModel model = new DefaultTableModel(data, col);
JTable table = new JTable(model);
//call method to select rows (select all rows)
selectRows(table, 0, table.getRowCount());
//call method to return values of selected rows
ArrayList<Integer> values = getSelectedRowValues(table);
//prints out each values of the selected rows
for (Integer integer : values) {
System.out.println(integer);
}
frame.getContentPane().add(new JScrollPane(table));
}
private void selectRows(JTable table, int start, int end) {
// Use this mode to demonstrate the following examples
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
// Needs to be set or rows cannot be selected
table.setRowSelectionAllowed(true);
// Select rows from start to end if start is 0 we change to 1 or leave it (used to preserve coloums headers)
table.setRowSelectionInterval(start, end - 1);
}
/**
* Will return all selected rows values
*
* @param table
* @return ArrayList<Intger> values of each selected row for all coloumns
*/
private ArrayList<Integer> getSelectedRowValues(JTable table) {
ArrayList<Integer> values = new ArrayList<>();
int[] vals = table.getSelectedRows();
for (int i = 0; i < vals.length; i++) {
for (int x = 0; x < table.getColumnCount(); x++) {
System.out.println(table.getValueAt(i, x));
values.add(Integer.parseInt((String) table.getValueAt(i, x)));
}
}
return values;
}
}
魔法发生在这里:
private void selectRows(JTable table, int start, int end) {
// Use this mode to demonstrate the following examples
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
// Needs to be set or rows cannot be selected
table.setRowSelectionAllowed(true);
// Select rows from start to end if start is 0 we change to 1 or leave it (used to preserve coloums headers)
table.setRowSelectionInterval(start, end - 1);
}
有关更多示例,请查看此处向您展示如何使用SelectionModel
on JTable
for rows 和 colomns