Java Program to deselect all cells in a JTable


At first, let’s say, we have selected a row using addRowSelectionInterval() as shown in the demo screenshot −

Now, we will deselect all these cells using clearSelection() as shown in the following example. This method clears the selected cells from the table −

Example

package my;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      DefaultTableModel tableModel = new DefaultTableModel();
      JTable table = new JTable(tableModel);
      tableModel.addColumn("Language/ Technology");
      tableModel.addColumn("Text Tutorial");
      tableModel.addColumn("Video Tutorial");
      tableModel.addColumn("Interview QA");
      tableModel.addRow(new Object[] { "ASP.NET", "Yes", "Yes", "Yes"});
      tableModel.addRow(new Object[] { "F#", "Yes", "No", "Yes"});
      tableModel.addRow(new Object[] { "SharePoint", "Yes", "Yes", "Yes"});
      tableModel.addRow(new Object[] { "AWS", "No", "No", "Yes"});
      tableModel.addRow(new Object[] { "Blockchain", "Yes", "No", "Yes"});
      tableModel.addRow(new Object[] { "C#", "Yes", "Yes", "Yes"});
      tableModel.addRow(new Object[] { "Java", "Yes", "No", "Yes"});
      tableModel.addRow(new Object[] { "NodeJS", "No", "Yes", "Yes"});
      tableModel.addRow(new Object[] { "MVC", "Yes", "No", "Yes"});
      // selected a row
      table.addRowSelectionInterval(2, 2);
      // deselecting
      table.clearSelection();
      JFrame f = new JFrame();
      f.setSize(600, 400);
      f.add(new JScrollPane(table));
      f.setVisible(true);
   }
}

Following is the output. Now you can see none of the cell is selected −

Output

Updated on: 30-Jul-2019

279 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements