문제

I've a JComboBox in 3rd and 4th column of a JTable but I don't know how to get its items...the problem isn't the method to get items but the cast

JComboBox combo=(JComboBox) jTable1.getColumnModel().getColumn(3).getCellEditor();

Can you help me please?

도움이 되었습니까?

해결책

The JComboBox is wrapped in a CellEditor. You must retrieve the wrapped component, for example when using DefaultCellEditor:

DefaultCellEditor editor = (DefaultCellEditor)table.getColumnModel().getColumn(3).getCellEditor();
JComboBox combo = (JComboBox)editor.getComponent();

다른 팁

Read this tutorial on how to use JCombobox as editor in JTable.
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#combobox

Try something like this:

 public void example(){  

      TableColumn tmpColum =table.getColumnModel().getColumn(1);
      String[] DATA = { "Data 1", "Data 2", "Data 3", "Data 4" };
      JComboBox comboBox = new JComboBox(DATA);

      DefaultCellEditor defaultCellEditor=new DefaultCellEditor(comboBox);
      tmpColum.setCellEditor(defaultCellEditor);
      tmpColum.setCellRenderer(new CheckBoxCellRenderer(comboBox));
      table.repaint();
   }


/**
   Custom class for adding elements in the JComboBox.
*/
class CheckBoxCellRenderer implements TableCellRenderer {
        JComboBox combo;
        public CheckBoxCellRenderer(JComboBox comboBox) {
            this.combo = new JComboBox();
            for (int i=0; i<comboBox.getItemCount(); i++){
                combo.addItem(comboBox.getItemAt(i));
            }
        }
        public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            combo.setSelectedItem(value);
            return combo;
        }
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top