Set whether the row in the table model can be selected or deselected in Java?

Java 8Object Oriented ProgrammingProgramming

We can set or disallow selection of row in the table using setRowSelectionAllowed().

Let’s say the following is our table −

DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);

If you want to allow selection of row, then set the method to TRUE −

table.setRowSelectionAllowed(true);

If you want to disallow selection of row, then set the method to FALSE −

table.setRowSelectionAllowed(false);

We have disallowed selection of rows in the below example −

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[] { "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"});
      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"});
      table.setRowHeight(3, 30);
      table.setRowSelectionAllowed(false);
      JFrame f = new JFrame();
      f.setSize(600, 400);
      f.add(new JScrollPane(table));
      f.setVisible(true);
   }
}

The output is as follows. Now you won’t be able to select a row −

Output

raja
Published on 31-May-2019 10:52:14
Advertisements