5

如何选择表中的所有行而不用户用鼠标选择它们?例如,我在一张名为InputTable. 使用ActionListener/ TableModelListener,我可以通过这种方式在表格中获取选定的行(当用户单击它们时):

int[] rows = inputTable.getSelectedRows();

我现在想选择 Input 表中的所有行并将其分配给int [] rows1. 有没有像getSelectedRows()我可以在没有用户交互的情况下选择所有行的命令?我知道有一个SelectAll(),但我想要一些特定于行的东西。

4

3 回答 3

5

我认为您正在尝试以编程方式选择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);
    }

有关更多示例,请查看此处向您展示如何使用SelectionModelon JTablefor rows 和 colomns

于 2012-09-28T13:01:53.683 回答
1

如果我正确理解了您的问题,则您存储了先前(或所需)的选择,并且您想要恢复该选择:

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

最后说明:如果您想/必须多次选择相同的索引,存储连续范围是有利可图的,这样您就不必每次都检测它们。sm.addSelectionInterval()基本上,这意味着在上面的代码示例中存储您传递给方法的范围:

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

// Detect and store continuous index ranges:
final List< int[] > idxRangeList = new ArrayList< int[] >();

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, store it
        idxRangeList.add( new int[] { 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 )
     idxRangeList.add( new int[] { rangeFirst, previous } );

// And now if you want those ranges selected:
final ListSelectionModel sm = inputTable.getSelectionModel();
sm.clearSelection(); // First clear selection

for ( final int[] range : idxRangeList )
    sm.addSelectionInterval( range[ 0 ], range[ 1 ] );
于 2012-09-28T09:45:23.923 回答
1

如果您在构造函数中执行 selectAll() 函数,它应该选择孔表而无需任何用户交互。

  private void createAndShowUI() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    initComponents(frame);
    frame.pack();
    frame.setVisible(true);
    table.selectAll();
}
于 2015-07-23T15:25:34.973 回答