简体   繁体   English

如何使JTable单元在单击时执行与双击不同的操作?

[英]How can I make a JTable cell do different things on single-click than on double-click?

I am using an editable JTable that contains a column named Subject. 我正在使用包含名为Subject的列的可编辑JTable When the first row is empty and the user clicks on a subject cell to add new task, by default, the user has to click twice to make the cell editable. 当第一行为空且用户单击主题单元格以添加新任务时,默认情况下,用户必须单击两次才能使单元格可编辑。 I want to make it editable on single-click and have it open another form on double-click. 我想让它在单击时可编辑,并在双击时打开另一个表单。 I have tried MouseListener but have not been able to solve it. 我尝试过MouseListener但无法解决它。 Is there a way to solve this problem? 有没有办法解决这个问题? If so, what is it? 如果是这样,它是什么?

My code: 我的代码:

class mouseRenderer extends DefaultTableCellRenderer {
    JLabel lblcell = new JLabel();

    public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row,
            int column) {
        ttable.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                selrow = ttable.getSelectedRow();
                selcol = ttable.getSelectedColumn();

                if(e.getClickCount() == 1) {
                    if(selrow == 0) {
                        lblcell.setText("");
                    }
                }
            }
        });
        return lblcell;
    }
}

只需单击即可编辑,您可以尝试使用jtable中使用的celleditor的'setClickCountToStart()'方法。

You can try to create a custom CellEditor like this one and set it with setCellEditor() 您可以尝试创建这样的自定义CellEditor并使用setCellEditor()

public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {

    public boolean isCellEditable(EventObject evt) {
        if (evt instanceof MouseEvent) {
            int clickCount;

            // For single-click activation
            clickCount = 1;

            // For double-click activation
            clickCount = 2;

            // For triple-click activation
            clickCount = 3;

            return ((MouseEvent)evt).getClickCount() >= clickCount;
        }
        return true;
    }
}

The MouseListener is the way to go for capturing double clicks on a row. MouseListener是捕获行上双击的方法。 It should work fine. 它应该工作正常。

As far as one-click to edit, you might want to select rows using a MouseMotionListener and let the JTable take the single-click to edit. 只需单击即可编辑,您可能希望使用MouseMotionListener选择行,并让JTable单击进行编辑。 Another option might be to use a MouseListener to detect the cell that was clicked, but that is getting a little messy. 另一种选择可能是使用MouseListener来检测被单击的单元格,但这有点混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM