如何使用JComboBox使JTable只响应双击而不是单击

时间:2017-08-20 07:44:46

标签: java swing jtable tablecelleditor

这是我第一次尝试使用CellEditorsJTable嵌入JComboBoxJSpinner。一切正常,我可以看到JComboBox模型中的值以及JSpinner的模型值。

但是,我注意到只要单击JTable的JComboBox列就会显示JComboBox的值。

它不是非常用户友好,因为我认为用户更愿意双击JTable的列来获取下拉框值并从中选择值而不是单击

如何将JComboBox的行为更改为仅在双重点击时显示?

我以为我会向MouseListener申请JComboBox,但我不知道接下来要做什么。

这是我到目前为止所写的内容。

public class ScheduleDayCellEditor extends DefaultCellEditor{
    private JComboBox jcmbDays;
    private JTable jtblSchedule;
    private DefaultComboBoxModel model;

    public ScheduleDayCellEditor(){
        super(new JComboBox());
        model = new DefaultComboBoxModel(new String[]{"Mon","Tue","Wed","Thu","Fri"});
        jcmbDays = new JComboBox(model);
        jcmbDays.setEditable(false);
        jcmbDays.setSelectedIndex(-1);

        jcmbDays.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(e.getClickCount() == 2){
                    //? ? ? ?
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        return jcmbDays;
    }

    @Override
    public Object getCellEditorValue() {
        return jcmbDays.getSelectedItem(); //To change body of generated methods, choose Tools | Templates.
    }

以下是其他说明的屏幕截图。

enter image description here

我很感激任何帮助。

谢谢。

2 个答案:

答案 0 :(得分:1)

通过应用更多标准简单地覆盖isCellEditable:

@Override
public boolean isCellEditable(EventObject aAnEvent) {
    boolean cellEditable = super.isCellEditable(aAnEvent);

    if (cellEditable && aAnEvent instanceof MouseEvent) {
        cellEditable = ((MouseEvent) aAnEvent).getClickCount() == 2;
    }

    return cellEditable;
}

答案 1 :(得分:1)

如果您因某些其他原因而无法 延长DefaultCellEditor,则只需使用count {2方法调用其setClickCountToStart()方法即可{1}}。

DefaultCellEditor editor = new DefaultCellEditor(jcmbDays);
editor.setClickCountToStart(2);
jcmbColumn.setCellEditor(editor);