JComboBox自定义编辑器JTable

时间:2014-11-29 12:24:26

标签: java swing jtable jcombobox cellrenderer

我想将Jtable添加到JComboBox Editor中,所以当我选择ComboBox时,JTable会出现。

我不能使用table.removeActionListener()和table.addActionListener()。我们新功能

table.addAncestorListener(addAncestorListener listener)和

table.removeAncestorListener(addAncestorListener listener)

到目前为止,她是我的代码,

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 ; 

    }

}

她是一张图片说明了我想要的东西

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

1 个答案:

答案 0 :(得分:1)

虽然在技术上可以将JTable用作ComboBoxEditor,但结果可能不实用。而是将TableModel的所需实例添加到组合ComboBoxModel,并使用setModel()在相邻的JTable中显示所选模型。总结如下,显示了一个完整的示例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);
    }
});