要实现“编辑JComboBox后,项目列表会在另一个JComboBox单元格下打开”的效果,可以使用JTable来创建一个带有多个列和行的表格,并在其中的一个列中使用JComboBox作为编辑器。
以下是一个示例代码:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ComboBoxTableExample extends JFrame {
private JTable table;
private DefaultTableModel model;
public ComboBoxTableExample() {
model = new DefaultTableModel(new Object[]{"Name", "Status"}, 0);
table = new JTable(model);
table.getColumnModel().getColumn(1).setCellEditor(new CustomComboBoxEditor());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
public void addData(String name, String status) {
model.addRow(new Object[]{name, status});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ComboBoxTableExample frame = new ComboBoxTableExample();
frame.setVisible(true);
frame.addData("Item 1", "Status 1");
frame.addData("Item 2", "Status 2");
frame.addData("Item 3", "Status 3");
}
});
}
private class CustomComboBoxEditor extends DefaultCellEditor {
private JComboBox comboBox;
public CustomComboBoxEditor() {
super(new JComboBox());
comboBox = (JComboBox) getComponent();
comboBox.addItem("Status 1");
comboBox.addItem("Status 2");
comboBox.addItem("Status 3");
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stopCellEditing();
}
});
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
comboBox.setSelectedItem(value);
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
@Override
public Object getCellEditorValue() {
return comboBox.getSelectedItem();
}
}
}
在这个示例中,我们创建了一个带有两列的JTable,其中第二列使用了自定义的编辑器CustomComboBoxEditor,该编辑器使用JComboBox来编辑单元格的值。当用户编辑JComboBox并选择一个新的项目时,编辑器将停止编辑并将新的项目值保存到单元格中。
在main方法中,我们添加了一些示例数据到表格中,以便在程序启动时显示。
运行示例代码后,你将看到一个带有两列的表格,其中第二列使用JComboBox作为编辑器。当你单击第二列的单元格时,JComboBox将打开并显示项目列表。