Select all rows in a table using JTable

How to select all rows in a table without user selecting a mouse? For example, I have a table called InputTable. Using ActionListener/ TableModelListener, I can get the selected rows (when the user clicks on them) in the table somewhat in this way:

int[] rows = inputTable.getSelectedRows();

Now I would like to select all rows in the table Input and assign him int [] rows1. Is there a command like getSelectedRows()where I can select all rows without user interaction? I know there is SelectAll(), but I want something specific for strings only.

+5
source share
3 answers

I think you are trying to programmatically select rows JTable.

JTable - . () SelectionModel, , :

enter image description here

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 JTable colomns

+5

, ( ) , :

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 ] );
+1

If you execute the selectAll () function in the constructor, it must select the hole table without any user interaction.

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

All Articles