TodayILearned
TodayILearned

Reputation: 1500

How to perform move mouse and click action?

My objective is to move the mouse to

1) scrollbar zone and
2) click so that scrollbar will move down.

I am using the Robot class to perform the move mouse operation, but not able to click on the scrollbar zone.

Robot rb=new Robot();
rb.mouseMove(1135,400);
Thread.sleep(5000);
Actions act=new Actions(driver);
act.click().perform();

Please help me in resolving the issue.

Upvotes: 2

Views: 1329

Answers (1)

Gacci
Gacci

Reputation: 1398

Ok, so here it is a very general demo. You can easily adapt it to your needs. If you want to use different heights in the scroll, you have to take into account that the time (one second) I used would be greater the higher the scroll pane. However, for a generic one you can detect when the scroll pane is a the bottom and no longer call the timer. I commented the part you can use to make it generic.

import java.util.Timer;
import java.util.TimerTask; 
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import java.awt.Dimension;

import java.awt.Robot;
import java.awt.event.InputEvent;

public class Stackoverflow extends JFrame{
    private java.util.Timer timer;
    private JFrame window;
    public static void main(String [] args){
        new Stackoverflow();
    }
    public Stackoverflow(){
        JPanel panel = new JPanel();
        panel.setPreferredSize(new Dimension(500, 2000));
        panel.setOpaque(false);


        this.window = this;
        this.timer = new java.util.Timer();
        timer.schedule(new AutoSaveTasker(), 1000);         

        this.add(new JScrollPane(panel));
        this.pack();
        this.setVisible(true);
    }
    class AutoSaveTasker extends TimerTask{
        @Override
        public void run(){
            /*
            if(scroll not at the bottom yet?) 
                then call timer again like this /timer.schedule(new AutoSaveTasker(), INTERVAL);
            */
            try{

                Robot robot = new Robot();
                robot.mouseMove(window.getWidth() - 10, window.getHeight() - 10);
                robot.mousePress(InputEvent.BUTTON1_MASK);
                Thread.sleep(1000);
                robot.mouseRelease(InputEvent.BUTTON1_MASK);
            }
            catch(Exception e){
                e.printStackTrace();
            }

        }
    }
}

Upvotes: 1

Related Questions