我在设置JComboBox时遇到了问题。在separte面板上为用户提供了一些选项,用于确定是否应该启用/禁用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();
}
* TableCellRenderer *
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;
}
}
* DefaultCellEditor *
public class MyComboBoxEditor extends DefaultCellEditor {
private static final long serialVersionUID = 1L;
public MyComboBoxEditor(String[] items) {
super(new JComboBox(items));
}
}
任何关于我做错什么的指示都会非常感激!!
谢谢,
答案 0 :(得分:2)
不要将JComponents
存储在XxxTableModel
中,然后JComboBox
中的最后一个选定值存储在XxxTableModel
中String value
答案 1 :(得分:2)
如果要禁用表格中单元格的版本,则应覆盖TableModel.isCellEditable(int,int)
这里你要做的就是渲染一个禁用的JComboBox,但这不会阻止编辑,它只是渲染一个禁用的JComboBox。另请参阅http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#editrender