我已经阅读了大多数JTable / JComboBox对此类其他问题的回复,但还没有找到解决我问题的方法.
我创建了一个具有JComboBox TableHeader元素的表.没有任何JComboBox元素将打开以显示项目列表.如何获取要显示的各个JComboBox元素的项目列表?
请注意,此问题的一个显着特征是JComboBox位于TableHeader中,未嵌入JTable单元中.
任何帮助表示赞赏.
SSCE
import java.awt.Component;
import java.awt.Dimension;
import java.util.Enumeration;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
public class ComboHeaderTest extends JScrollPane {
private static final Dimension DEFAULT_SIZE = new Dimension(200,200);
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ComboHeaderTest().initComponents();
}
});
}
private ComboHeaderTest() {
final String[][] data = { {"Header 1","Header 2","Header 3"},{"A","B","C"},{"D","E","F"},{"G","H","I"}};
setViewportView(getTable(data));
setPreferredSize(DEFAULT_SIZE);
}
private void initComponents() {
JFrame frame = new JFrame("ComboHeaderTest");
frame.add(this);
frame.pack();
frame.setVisible(true);
}
private JTable getTable(final String[][] data) {
final String[] items = data[0];
final ComboHeaderRenderer[] columnHeaders = new ComboHeaderRenderer[items.length];
for(int i = 0; items.length > i; ++i) {
columnHeaders[i] = new ComboHeaderRenderer(items);
}
final JTable table = new JTable(data,columnHeaders);
final EnumerationBox implements TableCellRenderer{
public ComboHeaderRenderer(final String[] entries) {
for (int i = 0; entries.length > i; ++i) {
addItem(entries[i]);
}
}
@Override
public Component getTableCellRendererComponent(final JTable table,final Object value,final boolean isSelected,final boolean hasFocus,final int row,final int column) {
setSelectedItem(value);
return this;
}
}
}
最佳答案