Java Swing How to - Keep JTable selection








Question

We would like to know how to keep JTable selection.

Answer

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
/*from w w  w  . j  a  v  a 2s  .com*/
public class Main {

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTable t = new JTable(10, 1);
    frame.add(new JScrollPane(t));

    t.getSelectionModel().clearSelection();
    t.getSelectionModel().addSelectionInterval(5, 6);
    t.getSelectionModel().addSelectionInterval(8, 8);
    frame.pack();
    frame.setVisible(true);
  }

}