我在设置 JComboBox 时遇到问题。在单独的面板上为用户提供了一些选项,这些选项确定是否应该启用/禁用 JComboBox - 我遇到的问题是,即使在 JComboBox 被禁用时,用户仍然可以从 JComboBox 中进行选择(它被禁用,因为组合框是灰色的)!JComboBox 使用自定义 TableCellRenderer 和自定义 DefaultCellEditor。JComboBox 也是 JTable 的一行中的一个单元格/列。
所以这里是代码的细分:
* JTable 的prepareRenderer *
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
JComponent component = (JComponent) super.prepareRenderer(renderer, row, column);
//Code which checks to see if component should be enabled
enableComponent = false;
component.setEnabled(enableComponent);
}
*设置组合框*
public void setupUserCombo(){
TableColumn col = getColumnModel().getColumn(0);
List<String> comboUsers = new String["Adam", "Ben"]
MyComboBoxRenderer jComboBox = (new MyComboBoxRenderer((String[])values.toArray(comboUsers ));
col.setCellEditor(new MyComboBoxEditor((String[])values.toArray(new String[0])));
col.setCellRenderer(jComboBox);
repaint();
}
*表格单元渲染器 *
public class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
private static final long serialVersionUID = 1L;
public MyComboBoxRenderer(String[] items) {
super(items);
repaint();
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
setSelectedItem("");
if (isSelected) {
super.setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setSelectedItem(value);
return this;
}
}
*默认单元格编辑器 *
public class MyComboBoxEditor extends DefaultCellEditor {
private static final long serialVersionUID = 1L;
public MyComboBoxEditor(String[] items) {
super(new JComboBox(items));
}
}
任何关于我做错了什么的指针将不胜感激!
谢谢,