
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements