Java : detect triple-click without firing double-click

前端 未结 7 1012
旧巷少年郎
旧巷少年郎 2021-01-19 17:40

I have a JTable in which I want to call a function when a cell is double-clicked and call another function when the cell is triple-clicked.

When the cell is triple-c

7条回答
  •  春和景丽
    2021-01-19 18:39

    You can do something like that, varying delay time:

    public class ClickForm extends JFrame {
    
    final static long CLICK_FREQUENTY = 300;
    
    static class ClickProcessor implements Runnable {
    
        Callable eventProcessor;
    
        ClickProcessor(Callable eventProcessor) {
            this.eventProcessor = eventProcessor;
        }
    
        @Override
        public void run() {
            try {
                Thread.sleep(CLICK_FREQUENTY);
                eventProcessor.call();
            } catch (InterruptedException e) {
                // do nothing
            } catch (Exception e) {
                // do logging
            }
        }
    }
    
    public static void main(String[] args) {
        ClickForm f = new ClickForm();
        f.setSize(400, 300);
        f.addMouseListener(new MouseAdapter() {
            Thread cp = null;
            public void mouseClicked(MouseEvent e) {
                System.out.println("getClickCount() = " + e.getClickCount() + ", e: " + e.toString());
    
                if (cp != null && cp.isAlive()) cp.interrupt();
    
                if (e.getClickCount() == 2) {
                    cp = new Thread(new ClickProcessor(new Callable() {
                        @Override
                        public Void call() throws Exception {
                            System.out.println("Double click processed");
                            return null;
                        }
                    }));
                    cp.start();
                }
                if (e.getClickCount() == 3) {
                    cp =  new Thread(new ClickProcessor(new Callable() {
                        @Override
                        public Void call() throws Exception {
                            System.out.println("Triple click processed");
                            return null;
                        }
                    }));
                    cp.start();
                }
            }
        });
        f.setVisible(true);
    }
    }
    

提交回复
热议问题