user250093
user250093

Reputation:

How to add a JComboBox to a JTable cell?

I am trying to add JComponents to JTable Cells. Do I Implement CellRenderer or CellEditor?

Upvotes: 7

Views: 6940

Answers (3)

Walid Bousseta
Walid Bousseta

Reputation: 1469

1- Create a JCombobox and insert into it the information you want, like this:

JComboBox<String> sport = new JComboBox<String>();
sport.addItem("foot");
sport.addItem("hand bool");
sport.addItem("****");

2- Create a JTable and set a Table Mode to this table, something like:

Vector<String> title = new Vector<String>
title.add("id");
title.add("sport");
Vector<Vector<String>> rows = new Vector<Vector<String>>();
rows.addItem("1");
rows.addItem("2");

JTable table = new JTable(rows, title);

3- You put the JComboBox in JTable Cells like this:

table.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(sport));

Upvotes: 0

willcodejavaforfood
willcodejavaforfood

Reputation: 44103

You could also do it with the DefaultCellEditor by passing in an instance of a JComboBox (or JCheckBox or JTextField) to the constructor.

Upvotes: 1

Carlos
Carlos

Reputation: 2513

What you need is a custom editor which will return the JComboBox (or whatever component you want to use). You should check the Sun tutorial for JTable, it contains an example on how to use a JComboBox as an editor. If you want to use JComboBox as a renderer as well, the tutorial applies to that too.

Upvotes: 7

Related Questions