
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
Select Different Cells of a JTable Programmatically in Java
A JTable is a subclass of JComponent class and it can be used to create a table with information displayed in multiple rows and columns. When a value is selected from a JTable, a TableModelEvent is generated, which is handled by implementing a TableModelListener interface.
In general, a user can select the rows and columns manually in a JTable, we can also select different cells of a JTable programmatically using setRowSelectionInterval() and setColumnSelectionInterval() methods of JTable class.
Example
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JTableCellSelectionTest extends JFrame { private JTable table; public JTableCellSelectionTest() { setTitle("JTableCellSelection Test"); Object[][] data = {{ "Raja", "Java", "Hyderabad"}, {"Vineet", "JavaScript", "Bangalore"}, {"Adithya", "Scala", "Chennai"}, {"Jai", "ServiceNow", "Pune"}, {"Chaitanya", "Python", "Noida"}, {"Krishna", "AI", "Mumbai"}}; String columns[] = {"Name", "Technology", "Location"}; table = new JTable(data, columns); add(new JScrollPane(table)); table.setRowSelectionInterval(0, 2); table.setColumnSelectionInterval(0, 2); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String []args) { new JTableCellSelectionTest(); } }
Output
Advertisements