JComboBox custom editor JTable

253 views Asked by At

I want to add Jtable to JComboBox Editor, so when i select the ComboBox the JTable show up.

I can't use table.removeActionListener() and table.addActionListener(). we new functions

table.addAncestorListener( addAncestorListener listener) and

table.removeAncestorListener(addAncestorListener listener)

her is my code so far,

public class CustomComboEditor implements ComboBoxEditor {
    private JTable table  ;
    public CustomComboEditor() {
        table = new JTable();
    }

    @Override
    public void addActionListener(ActionListener l) {

      // there is no addActionListener(l) for table

    }

    @Override
    public Component getEditorComponent() {
        return table ; 
    }

    @Override
    public Object getItem() {
        return table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
    }

    @Override
    public void removeActionListener(ActionListener l) {

        // there is no removeActionListener(l);for table
    }

    @Override
    public void selectAll() {
        table.selectAll();

    }

    @Override
    public void setItem(Object anObject) {
        return ; 

    }

}

her is an image illustrates what i want exactly

combobox table editor http://im47.gulfup.com/ECk9HK.png

1

There are 1 answers

0
trashgod On

While it may be technically possible to use a JTable as a ComboBoxEditor, the result may be unwieldy. Instead, add the desired instances of your TableModel to the combo's ComboBoxModel and use setModel() to display the selected model in an adjacent JTable. Summarized below, a complete example is shown here.

image

DefaultComboBoxModel dcbm = new DefaultComboBoxModel();
private JComboBox combo = new JComboBox(dcvm);
…
for (int i = 0; i < N; i++) {
    …
    TableModel model = new YourTableModelModel(name);
    dcbm.addElement(model);
}
…
combo.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        TableModel model = (TableModel) combo.getSelectedItem();
        table.setModel(model);
    }
});