JComboBox 作为自定义 TableCellEditor

发布于 2024-12-07 10:01:14 字数 993 浏览 1 评论 0原文

我有一张桌子。该表上的更改会更新数据库。该表中的一列由 JComboBox 编辑。单击该列中的任何单元格都会触发 tableChanged 事件。但是,在选择 JComboBox 的项目后需要触发它。如何让 tableChanged 在选择后发生?

public class JIDCellEditor extends AbstractCellEditor implements TableCellEditor {

    JComboBox jComboBox;

    @Override
    public Object getCellEditorValue() {
        return jComboBox.getSelectedItem();
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        Vector vector = new Vector();
        vector.add(0);
        for (int i = 0; i < table.getRowCount(); i++) {
            if (!vector.contains(table.getValueAt(i, 0)) && table.getValueAt(i, 3).toString().equals("Female")) {
                vector.add(table.getValueAt(i, 0));
            }
        }
        vector.remove(table.getValueAt(row, 0));
        jComboBox = new JComboBox(vector);
        jComboBox.setSelectedItem(value);
        return jComboBox;
    }
}

I have a table. Changes on that table update database. One column is edited by a JComboBox in that table. Clicks to any cell in that column fires a tableChanged event. However it needs to be fired after selecting an item of a JComboBox. How can i make tableChanged occur after selection?

public class JIDCellEditor extends AbstractCellEditor implements TableCellEditor {

    JComboBox jComboBox;

    @Override
    public Object getCellEditorValue() {
        return jComboBox.getSelectedItem();
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        Vector vector = new Vector();
        vector.add(0);
        for (int i = 0; i < table.getRowCount(); i++) {
            if (!vector.contains(table.getValueAt(i, 0)) && table.getValueAt(i, 3).toString().equals("Female")) {
                vector.add(table.getValueAt(i, 0));
            }
        }
        vector.remove(table.getValueAt(row, 0));
        jComboBox = new JComboBox(vector);
        jComboBox.setSelectedItem(value);
        return jComboBox;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

累赘 2024-12-14 10:01:14

我强烈建议使用 SwingX ,它有一个 ComboBoxCellEditor 组件。它本质上是 Sun 的 Swing 组件应有功能的孵化器。我不知道该项目是否仍在积极开发中,但它已经成熟,并且我已经在很多项目中使用了它。

如果出于某种原因,您不能或不想使用外部库,这里是他们的代码(修改了部分以删除自定义 SwingX 功能),注释完好无损:

注意:该库是 GPL 代码。

/*
 * $Id: ComboBoxCellEditor.java 3738 2010-07-27 13:56:28Z bierhance $
 * 
 * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved.
 * 
 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.util.EventObject;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;

/**
 * <p>
 * This is a cell editor that can be used when a combo box (that has been set up for automatic completion) is to be used in a JTable. The
 * {@link javax.swing.DefaultCellEditor DefaultCellEditor} won't work in this case, because each time an item gets selected it stops cell
 * editing and hides the combo box.
 * </p>
 * <p>
 * Usage example:
 * </p>
 * <p>
 * 
     * <pre>
 * <code>
 * JTable table = ...;
 * JComboBox comboBox = ...;
 * ...
 * TableColumn column = table.getColumnModel().getColumn(0);
 * column.setCellEditor(new ComboBoxCellEditor(comboBox));
 * </code>
 * </pre>
 * 
 * </p>
 */
public class ComboBoxCellEditor extends DefaultCellEditor {

    /**
     * Creates a new ComboBoxCellEditor.
     * 
     * @param comboBox the comboBox that should be used as the cell editor.
     */
    public ComboBoxCellEditor(final JComboBox comboBox) {
        super(comboBox);

        comboBox.removeActionListener(this.delegate);

        this.delegate = new EditorDelegate() {
            @Override
            public void setValue(final Object value) {
                comboBox.setSelectedItem(value);
            }

            @Override
            public Object getCellEditorValue() {
                return comboBox.getSelectedItem();
            }

            @Override
            public boolean shouldSelectCell(final EventObject anEvent) {
                if (anEvent instanceof MouseEvent) {
                    final MouseEvent e = (MouseEvent) anEvent;
                    return e.getID() != MouseEvent.MOUSE_DRAGGED;
                }
                return true;
            }

            @Override
            public boolean stopCellEditing() {
                if (comboBox.isEditable()) {
                    // Commit edited value.
                    comboBox.actionPerformed(new ActionEvent(ComboBoxCellEditor.this, 0, ""));
                }
                return super.stopCellEditing();
            }

            @Override
            public void actionPerformed(final ActionEvent e) {
                ComboBoxCellEditor.this.stopCellEditing();
            }
        };
        comboBox.addActionListener(this.delegate);
    }
}

I would highly recommend using SwingX which has a ComboBoxCellEditor component. It's essentially Sun's incubator for features Swing components should have. I have no idea if the project is still actively developed, but its mature, and I've used it in many projects.

If, for whatever reason, you can't or don't want to use an external library, here is their code (with parts modified to remove custom SwingX features), comments intact:

Note: the library is GPL'ed code.

/*
 * $Id: ComboBoxCellEditor.java 3738 2010-07-27 13:56:28Z bierhance $
 * 
 * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved.
 * 
 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.util.EventObject;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;

/**
 * <p>
 * This is a cell editor that can be used when a combo box (that has been set up for automatic completion) is to be used in a JTable. The
 * {@link javax.swing.DefaultCellEditor DefaultCellEditor} won't work in this case, because each time an item gets selected it stops cell
 * editing and hides the combo box.
 * </p>
 * <p>
 * Usage example:
 * </p>
 * <p>
 * 
     * <pre>
 * <code>
 * JTable table = ...;
 * JComboBox comboBox = ...;
 * ...
 * TableColumn column = table.getColumnModel().getColumn(0);
 * column.setCellEditor(new ComboBoxCellEditor(comboBox));
 * </code>
 * </pre>
 * 
 * </p>
 */
public class ComboBoxCellEditor extends DefaultCellEditor {

    /**
     * Creates a new ComboBoxCellEditor.
     * 
     * @param comboBox the comboBox that should be used as the cell editor.
     */
    public ComboBoxCellEditor(final JComboBox comboBox) {
        super(comboBox);

        comboBox.removeActionListener(this.delegate);

        this.delegate = new EditorDelegate() {
            @Override
            public void setValue(final Object value) {
                comboBox.setSelectedItem(value);
            }

            @Override
            public Object getCellEditorValue() {
                return comboBox.getSelectedItem();
            }

            @Override
            public boolean shouldSelectCell(final EventObject anEvent) {
                if (anEvent instanceof MouseEvent) {
                    final MouseEvent e = (MouseEvent) anEvent;
                    return e.getID() != MouseEvent.MOUSE_DRAGGED;
                }
                return true;
            }

            @Override
            public boolean stopCellEditing() {
                if (comboBox.isEditable()) {
                    // Commit edited value.
                    comboBox.actionPerformed(new ActionEvent(ComboBoxCellEditor.this, 0, ""));
                }
                return super.stopCellEditing();
            }

            @Override
            public void actionPerformed(final ActionEvent e) {
                ComboBoxCellEditor.this.stopCellEditing();
            }
        };
        comboBox.addActionListener(this.delegate);
    }
}
冰之心 2024-12-14 10:01:14

现在可以了。每次调用 getTableCellEditorComponent 方法时,都需要重新初始化 JComboBox。并且在此 JComboBox 的 itemstatechange 中 stopCellEditing() 方法必须通知侦听器在选择项目时已完成编辑。这使得 TableModelListener fireTableChanged 事件。 (已修复)但是,当您在单击另一个 JComboBox 而不进行选择后单击一个 JComboBox 时,它也会触发该事件。 (/已修复)

编辑:以下代码是最新版本。通过此 TableModelListener,仅当选择某个项目时才会收到通知。上述问题已解决。这是因为默认的 stopCellEditing() 方法总是返回 true。这会导致单元格编辑以意外的方式停止。必须根据需要重写它并 fireEditingStopped();必须用于通知TableModelListener

public class JIDCellEditor extends AbstractCellEditor implements TableCellEditor {

    private JComboBox jComboBox = new JComboBox();
    boolean cellEditingStopped = false;

    @Override
    public Object getCellEditorValue() {
        return jComboBox.getSelectedItem();
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        Vector vector = new Vector();
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        arrayList.add(Integer.parseInt(value.toString()));
        vector.add(0);
        for (int i = 0; i < table.getRowCount(); i++) {
            if (!vector.contains(table.getValueAt(i, 0)) && table.getValueAt(i, 3).toString().equals("Sheep")) {
                vector.add(table.getValueAt(i, 0));
            }
        }
        vector.remove(table.getValueAt(row, 0));

        for (int i = 0; i < vector.size(); i++) {
        }
        jComboBox = new JComboBox(vector);
        jComboBox.setSelectedItem(value);

        jComboBox.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    fireEditingStopped();
                }
            }
        });
        jComboBox.addPopupMenuListener(new PopupMenuListener() {

            @Override
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                cellEditingStopped = false;
            }

            @Override
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                cellEditingStopped = true;
                fireEditingCanceled();
            }

            @Override
            public void popupMenuCanceled(PopupMenuEvent e) {

            }
        });
        return jComboBox;
    }

    @Override
    public boolean stopCellEditing() {
        return cellEditingStopped;
    }
}

Now it works. JComboBox needs to be reinitialized every time getTableCellEditorComponent method invoked. And in the itemstatechange of this JComboBox stopCellEditing() method must notify listeners that editing done when item is selected. That make the TableModelListener fireTableChanged event. (Fixed) However it also fires that event when you click a JComboBox after clicking another JComboBox without making a selection. (/Fixed)

Edit: Following code is the last version. By this TableModelListener is notified only when an item is selected. The problem mentioned above is fixed. It was because of default stopCellEditing() method always returned true. This cause cell editing stop in an unexpected way. It must be overriden as needed and fireEditingStopped(); must be used to notify TableModelListener

public class JIDCellEditor extends AbstractCellEditor implements TableCellEditor {

    private JComboBox jComboBox = new JComboBox();
    boolean cellEditingStopped = false;

    @Override
    public Object getCellEditorValue() {
        return jComboBox.getSelectedItem();
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        Vector vector = new Vector();
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        arrayList.add(Integer.parseInt(value.toString()));
        vector.add(0);
        for (int i = 0; i < table.getRowCount(); i++) {
            if (!vector.contains(table.getValueAt(i, 0)) && table.getValueAt(i, 3).toString().equals("Sheep")) {
                vector.add(table.getValueAt(i, 0));
            }
        }
        vector.remove(table.getValueAt(row, 0));

        for (int i = 0; i < vector.size(); i++) {
        }
        jComboBox = new JComboBox(vector);
        jComboBox.setSelectedItem(value);

        jComboBox.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    fireEditingStopped();
                }
            }
        });
        jComboBox.addPopupMenuListener(new PopupMenuListener() {

            @Override
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                cellEditingStopped = false;
            }

            @Override
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                cellEditingStopped = true;
                fireEditingCanceled();
            }

            @Override
            public void popupMenuCanceled(PopupMenuEvent e) {

            }
        });
        return jComboBox;
    }

    @Override
    public boolean stopCellEditing() {
        return cellEditingStopped;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文