![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to add Combo Box to JTable
Use the JComboBox to add a combo box to a table -
JComboBox<String> comboBox = new JComboBox<>();
Now, add the combo box items -
comboBox.addItem("Asia"); comboBox.addItem("Europe"); comboBox.addItem("North America"); comboBox.addItem("South America");
Now, use the TableColumn and set the column wherein you want to set the above ComboBox items -
TableColumn testColumn = table.getColumnModel().getColumn(0);
Set the editor with the combo box -
testColumn.setCellEditor(new DefaultCellEditor(comboBox)); The following is an example to add JComboBox to JTable: package my; import java.awt.Color; import java.awt.Font; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumn; public class SwingDemo { public static void main(String[] argv) throws Exception { JTable table = new JTable(5, 5); Font font = new Font("Verdana", Font.PLAIN, 12); table.setFont(font); table.setRowHeight(30); table.setBackground(Color.orange); table.setForeground(Color.white); TableColumn testColumn = table.getColumnModel().getColumn(0); JComboBox<String> comboBox = new JComboBox<>(); comboBox.addItem("Asia"); comboBox.addItem("Europe"); comboBox.addItem("North America"); comboBox.addItem("South America"); comboBox.addItem("Africa"); comboBox.addItem("Antartica"); comboBox.addItem("Australia"); testColumn.setCellEditor(new DefaultCellEditor(comboBox)); JFrame frame = new JFrame(); frame.setSize(600, 400); frame.add(new JScrollPane(table)); frame.setVisible(true); } }
The output is as follows displaying JComboBox in JTable -
Output
Advertisements