开发者

JComboBox as CellRenderer does not set the correct value

I'm using a JComboBox as CellRenderer in my JTable.

Everything works fine the JComboBox displays the correct item for the corresponding row.

The problem I am currently working on is that when I choose a new value in the JComboBox (for example row 9) the value is set correctly, but when I try to change the value in the next row, the JComboBox (for example in row 10) automatically sets the value of the row before.

I created a DropDownCellRenderer class which extends JComboBox and implements TableCellRenderer, I thought that is enough, but it seems that the DropDownCellRenderer-object is the same for every row.

table.getColumnModel().getColumn( 3 ).setCellRenderer( new DropDownCellRenderer() );
table.getColumnModel().getColumn( 3 ).setCellEditor( new DefaultCellEditor( new DropDownCellRenderer() ) );

How can I avoid开发者_如何学Go that every row uses the same object?


Looked at your renderer's source code.

  1. I don't think you have to look up the Product by name. The value passed to you is the Product, which is coming from your table model (if it is implemented correctly). Just set the value as selected item and it should work.

  2. To make renderer behave correctly, change its foreground and background colors according to isSelected parameter. The code should look like:

    if (isSelected) {
        setForeground(table.getSelectionForeground());
        super.setBackground(table.getSelectionBackground());
    } else {
        setForeground(table.getForeground());
        setBackground(table.getBackground());
    }
    
  3. Make your initial array of values an argument of the constructor. This will transform your renderer into universal combobox renderer.


It sounds like you're saving and displaying values within the combo box itself, not from the model of the table. When you set a value and save a combobox value you need to update the model

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜