要将唯一的JComboBox添加到JTable(Java)中的列,您需要创建一个自定义的表格模型,该模型将包含一个JComboBox。以下是一个简单的示例,说明如何实现此目标:
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
public class ComboBoxTableModel extends AbstractTableModel {
private String[] columnNames = {"Column 1", "Column 2", "Column 3"};
private Object[][] data = {
{"Item 1", "Item 2", "Item 3"},
{"Item 4", "Item 5", "Item 6"},
{"Item 7", "Item 8", "Item 9"}
};
private JComboBox<String> comboBox = new JComboBox<>(new String[]{"Option 1", "Option 2", "Option 3"});
public ComboBoxTableModel() {
comboBox.setEditable(true);
}
@Override
public int getRowCount() {
return data.length;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return getValueAt(0, columnIndex).getClass();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
data[rowIndex][columnIndex] = value;
fireTableCellUpdated(rowIndex, columnIndex);
}
public JComboBox<String> getComboBox() {
return comboBox;
}
}
import javax.swing.*;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.*;
public class ComboBoxTableExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTable with ComboBox Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 400);
ComboBoxTableModel tableModel = new ComboBoxTableModel();
JTable table = new JTable(tableModel);
TableColumn column = table.getColumnModel().getColumn(1);
column.setCellRenderer(new ComboBoxRenderer(tableModel.getComboBox()));
column.setCellEditor(new ComboBoxEditor(tableModel.getComboBox()));
frame.add(new JScrollPane(table));
frame.setVisible(true);
}
}
import javax.swing.*;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
public class ComboBoxRenderer extends JComboBox<String> implements TableCellRenderer {
public ComboBoxRenderer(JComboBox<String> comboBox) {
setModel(comboBox.getModel());
setSelectedIndex(comboBox.getSelectedIndex());
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setSelectedItem(value);
return this;
}
}
class ComboBoxEditor extends DefaultCellEditor {
public ComboBoxEditor(JComboBox<String> comboBox) {
super(comboBox);
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
JComboBox<String> comboBox = (JComboBox<String>) getComponent();
comboBox.setSelectedItem(value);
return comboBox;
}
}
现在,您已经成功地将唯一的JComboBox添加到了JTable中的列。
领取专属 10元无门槛券
手把手带您无忧上云