我正在尝试将每个列单元格具有不同值的ComboBox加载到JTable中,但是我找不到实现此目的的任何方法。我在第一列中使用的代码如下:
Database database = Database.getInstance();
ResultSet resultSet = database.query("SELECT Titel from Serie");
while(resultSet.next())
{
comboBox.addItem(resultSet.getString("Titel"));
}
seriesColumn.setCellEditor(new DefaultCellEditor(comboBox));
根据返回的序列名称,执行一个新查询以获取每个序列的所有序列。因此,它们都会有所不同。以下是一些可以理解我的意思的图片:
第二列现在应根据第一列的顺序包含这些情节,但它们都是相同的。
任何帮助将不胜感激!
答案 0 :(得分:1)
该示例程序的主要部分是使用自定义单元格编辑器EpisodeEditor
。它根据第一列中选择的“系列”动态确定“情节”。
(我在本演示中使用了模拟数据源。)
import javax.swing.*;
import javax.swing.table.TableCellEditor;
import java.util.*;
public class ComboBoxTable
{
public static void main(String[] args)
{
// Mock data source
DataSource dataSource = new DataSource();
JComboBox<String> seriesComboBox = new JComboBox<>();
for (String s : dataSource.getSeries())
{
seriesComboBox.addItem(s);
}
JTable table = new JTable(
new String[][] {{"", ""}, {"", ""}, {"", ""}},
new String[] {"Series", "Episode"});
table.getColumn("Series").setCellEditor(new DefaultCellEditor(seriesComboBox));
table.getColumn("Episode").setCellEditor(new EpisodeEditor(dataSource));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(table));
f.setBounds(300, 200, 400, 300);
f.setVisible(true);
}
}
class EpisodeEditor extends AbstractCellEditor implements TableCellEditor
{
private DataSource dataSource;
private JComboBox<String> episodesComboBox = new JComboBox<>();
EpisodeEditor(DataSource dataSource)
{
this.dataSource = dataSource;
}
@Override
public java.awt.Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
int row, int column)
{
String series = (String) table.getModel().getValueAt(row, 0);
List<String> episodes = dataSource.getEpisodes(series);
episodesComboBox.removeAllItems();
for (String ep : episodes)
{
episodesComboBox.addItem(ep);
}
episodesComboBox.setSelectedItem(value);
return episodesComboBox;
}
@Override
public Object getCellEditorValue()
{
return episodesComboBox.getSelectedItem();
}
}
class DataSource
{
List<String> getSeries()
{
return Arrays.asList("Prison Break", "Breaking Bad", "Pokemon");
}
List<String> getEpisodes(String series)
{
switch (series)
{
case "Prison Break":
return Arrays.asList("Break 1", "Break 2", "Break 3");
case "Breaking Bad":
return Arrays.asList("Bad 1", "Bad 2", "Bad 3");
case "Pokemon":
return Arrays.asList("P1", "P2", "P3");
default:
throw new IllegalArgumentException("Invalid series: " + series);
}
}
}