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


We can set or disallow selection of column in the table using setColumnSelectionAllowed().

Let’s say the following is our table −

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

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

table.setColumnSelectionAllowed(true);

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

table.setRowSelectionAllowed(false);

Here, in the below example we have disallowed selection of columns −

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"});
      table.setRowHeight(3, 30);
      table.setColumnSelectionAllowed(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 column −

Output


Updated on: 30-Jul-2019

28 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements