Syntax error How to make JTable single selectable in Java?

How to make JTable single selectable in Java?



To make JTable single selectable in Java, you need to set the selection mode to be SINGE_SELECTION. Let’s say the following is our table −

String[][] rec = {
   { "001", "Shirts", "40" },
   { "002", "Trousers", "250" },
   { "003", "Jeans", "25" },
   { "004", "Applicances", "90" },
   { "005", "Mobile Phones", "200" },
   { "006", "Hard Disk", "150" },
};
String[] header = { "ID", "Product", "Quantity" };
JTable table = new JTable(rec, header);

Set the selection more to make it single selectable with setSelectionMode() method −

table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

Let us see an example to set the same for our table in Java −

Example

package my;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JPanel panel = new JPanel();
      panel.setBorder(BorderFactory.createTitledBorder(
         BorderFactory.createEtchedBorder(), "Stock", TitledBorder.CENTER, TitledBorder.TOP));
      String[][] rec = {
         { "001", "Shirts", "40" },
         { "002", "Trousers", "250" },
         { "003", "Jeans", "25" },
         { "004", "Applicances", "90" },
         { "005", "Mobile Phones", "200" },
         { "006", "Hard Disk", "150" },
      };
      String[] header = { "ID", "Product", "Quantity" };
      JTable table = new JTable(rec, header);
      table.setShowHorizontalLines(true);
      table.setGridColor(Color.blue);
      // make table single selectable
      table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      panel.add(new JScrollPane(table));
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}

Output

Updated on: 2019-07-30T22:30:26+05:30

280 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements