JTable - 列中每个单元格的不同 ComboBox

JTable - Different ComboBox for each cell in column

我正在尝试将每个列单元格具有不同值的 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));

并且根据返回的系列名称,执行新查询以获取系列的所有剧集,每个系列。所以他们都会不同。以下是一些图片,可以让您了解我的意思:

第二列现在应该包含根据第一列系列的剧集,但它们都是一样的。

如有任何帮助,我们将不胜感激!

这个示例程序的主要部分是自定义单元格编辑器的使用EpisodeEditor。它根据第一列中选​​择的 "series" 动态决定 "episodes"。

(我在本次演示中使用了模拟数据源。)

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);
    }
  }
}