JComboBox在JTable中恢复原始值

时间:2012-02-24 11:02:24

标签: java swing

我有一个JTable,在列的内部我有一个JComboBox。

我的表有自己的模型:见下文

package View;

public class CustomTableModel extends AbstractTableModel {

    ArrayList<Item> data;

    public String[] columnNames = {"ID", "Amount", "value", "bought", "quantity"};

    public CustomTableModel(ArrayList<Item>  data){
        this.data = data
    }

    public int getColumnCount() {
        return columnNames.length;
    }


    public int getRowCount() {
        return data.size();
    }

    @Override
    public Object getValueAt(int arg0, int arg1) {

        if(arg1 == 0){
            return data.get(arg0).getID();
        }

        if(arg1 == 1){
            return data.get(arg0).getAmount();
        }

        if(arg1 == 2){
            return data.get(arg0).getValue();
        }

    if(arg1 == 3){
        return data.get(arg0).isBought();
    }


    else {
        return data.get(arg0).getQuantity();
    }
}

  public String getColumnName(int index) {

      return columnNames[index];

  }

  @Override
  public void setValueAt(Object aValue, int row, int col) {
      if (col == 3) {
         data.get(row).setBought((Boolean) aValue);
          this.fireTableCellUpdated(row, col);

      }
  }

public boolean isCellEditable(int row, int col){
    return true;
}

public Class<?> getColumnClass(int columnIndex)  
{  
  if (columnIndex == 3 )  
  {  
    return Boolean.class;  
  }  

  else  

    return super.getColumnClass(4);  

} 

此Renderer和Editor应用于包含JComboBox的列;

public class ComboBoxRenderer extends JComboBox implements TableCellRenderer {
public ComboBoxRenderer(String[] items) {
    super(items);
}

public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
        setForeground(table.getSelectionForeground());
        super.setBackground(table.getSelectionBackground());
    } else {
        setForeground(table.getForeground());
        setBackground(table.getBackground());
    }


    setSelectedIndex(0);
    return this;
}


public class ComboBoxEditor extends DefaultCellEditor {
public ComboBoxEditor(String[] items) {
    super(new JComboBox(items));
}

public Object getCellEditorValue() {   
    return j.getEditor().getItem();   
 }  

框中应该显示应该包含的所有值,但是当我单击该框并选择另一个值时,只要我在页面上的其他位置导航,它就会恢复为原始值。然而有趣的是,如果我点击列中的任何JCombobox,它将突出显示我选择的新值!但它只显示原始的。

1 个答案:

答案 0 :(得分:1)

看起来问题是在模型中设置值。仅设置第3列值(布尔值)

public void setValueAt(Object aValue, int row, int col) { 
      if (col == 3) { 
         data.get(row).setBought((Boolean) aValue); 
          this.fireTableCellUpdated(row, col); 

      } 
  }