Java 使用JTable选择表中的所有行

Java 使用JTable选择表中的所有行,java,swing,jtable,Java,Swing,Jtable,如何选择表中的所有行,而不让用户用鼠标选择它们?例如,我有一个名为inputable的表。使用ActionListener/TableModelListener,我可以通过以下方式获得表中的选定行(当用户单击它们时): int[] rows = inputTable.getSelectedRows(); 现在我想选择输入表中的所有行,并将其指定为,int[]rows1。是否有类似于getSelectedRows()的命令,在该命令中我可以选择所有行而无需用户交互?我知道有一个SelectAll

如何选择表中的所有行,而不让用户用鼠标选择它们?例如,我有一个名为
inputable
的表。使用
ActionListener
/
TableModelListener
,我可以通过以下方式获得表中的选定行(当用户单击它们时):

int[] rows = inputTable.getSelectedRows();

现在我想选择输入表中的所有行,并将其指定为,
int[]rows1
。是否有类似于
getSelectedRows()
的命令,在该命令中我可以选择所有行而无需用户交互?我知道有一个
SelectAll()
,但我只想要特定于行的内容

如果我正确理解了您的问题,您已存储了以前(或所需)的选择,并且您希望恢复该选择:

int[] rowsToSelect = inputTable.getSelectedRows();
您可以稍后设置或恢复此选择,或将其恢复到其他表:

final ListSelectionModel sm = inputTable.getSelectionModel();
sm.clearSelection(); // First clear selection

for ( final int idx : rowsToSelect )
    sm.addSelectionInterval( idx, idx ); // Make this row selected
注意:如果首先对索引进行排序,并使用连续索引范围调用
addSelectionInterval()
,则可以提高性能:

Arrays.sort( rowsToSelect );  // You only have to sort if it is not yet sorted

final ListSelectionModel sm = inputTable.getSelectionModel();
sm.clearSelection(); // First clear selection

int rangeFirst = -1, previous = -1;
for ( final int idx : rowsToSelect ) {
    if ( rangeFirst < 0 )
        previous = rangeFirst = idx; // Start an index range
    else if ( idx != previous + 1 ) {
        // A continuous index range ends here, make it selected
        sm.addSelectionInterval( rangeFirst, previous );
        previous = rangeFirst = idx; // Start a new index range
    }
    else
       previous = idx; // Index range is continuous, proceed to the next index
}

// Add the last range which is not handled by the for loop:
if ( rangeFirst >= 0 )
    sm.addSelectionInterval( rangeFirst, previous );

我认为您正在尝试以编程方式选择
JTable
的行

JTable
只是一种显示机制。您不选择表(视图)中的行,而是选择表(视图)中的行,因此请看一下我制作的这个小示例:

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;
    }
}

有关更多示例,请查看如何在
JTable
上为行和列使用
SelectionModel
,如果在构造函数中执行selectAll()函数,则应在无任何用户交互的情况下选择孔表

  private void createAndShowUI() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    initComponents(frame);
    frame.pack();
    frame.setVisible(true);
    table.selectAll();
}

table.setRowSelectionInterval(0,table.getModel().getRowCount()-1)?你能更详细地解释一下吗?@SwethaP:在javadoc中有详细的描述。读一读。这就是javadoc的全部要点:被开发人员阅读。是的。但我的问题是获取类似int[]rows=inputable.getSelectedRows()的内容;我可以将所选行的索引存储在一个数组中。好的,显然我们没有抓住问题的关键。您知道如何
selectAll
,已经演示了如何
setRowSelectionInterval
仅选择一系列行,并且您知道如何
getSelectedRows
问题是什么??
    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);
    }
  private void createAndShowUI() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    initComponents(frame);
    frame.pack();
    frame.setVisible(true);
    table.selectAll();
}