Programmatically clicking a GUI button in Java Swing

前端 未结 6 914
灰色年华
灰色年华 2020-12-13 23:06

How would I programmatically click a Swing JButton in a way that would register all the relevant action/mouse events and be visible to the user (i.e. they\'d see the button

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 23:49

    Based on @Courteaux's answer, this method clicks the first cell in a JTable:

    private void clickFirstCell() {
        try {
            jTable1.changeSelection(0, 0, false, false);
            Point p = jTable1.getLocationOnScreen();
            Rectangle cellRect = jTable1.getCellRect(0, 0, true);
            Robot r = new Robot();
            Point mouse = MouseInfo.getPointerInfo().getLocation();
            r.mouseMove(p.x + cellRect.x + cellRect.width / 2, 
                    p.y + cellRect.y + cellRect.height / 2);
            r.mousePress(InputEvent.BUTTON1_MASK);
            try {
                Thread.sleep(50);
            } catch (Exception e) {
            }
            r.mouseRelease(InputEvent.BUTTON1_MASK);
            r.mouseMove(mouse.x, mouse.y);
        } catch (AWTException ex) {
        }
    }
    

提交回复
热议问题