问题
I have been working with simulating mouse events with the Robot class for a while, and all was well, until I tried to scroll using the mouseWheel function. I just have this simple line:
Robot robot = new Robot();
robot.mouseWheel(-100);
I have been trying variations of this for a long time, and the program runs, does nothing, then terminates normally. Can someone shed light on why this is?
Thanks!
回答1:
Your program might not be working because either there is nothing to scroll up
on the GUI to which your mouse pointer resting . Or, You have not rested your mouse pointer to the appropriate GUI on which you can see scroll effect. Here is the simple program to achieve that . I hope this would be of your help:
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.awt.*;
public class MouseScrollRobot extends JFrame
{
JTextArea ta;
boolean scrolledAway = false;
Robot robot;
boolean started = false;
public void createAndShowGUI()
{
setTitle("Robot Demonstration");
JPanel panel = new JPanel();
ta = new JTextArea();
StringBuilder sBuilder = new StringBuilder();
try
{
robot = new Robot();
BufferedReader bfr = new BufferedReader(new FileReader("MouseScrollRobot.java"));
String line = null ;
while ((line = bfr.readLine()) !=null)
{
sBuilder.append(line+"\n");
}
}
catch (Exception ex){ex.printStackTrace();}
ta.setText(sBuilder.toString());
JScrollPane jsp = new JScrollPane(ta);
final Timer timer = new Timer(100, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent evt)
{
try
{
robot.mouseMove((getLocationOnScreen().x + getWidth()) / 2 , (getLocationOnScreen().y + getHeight()) / 2);//Move mouse pointer to the Component which you want to scroll
ta.requestFocus();
robot.setAutoDelay(100);
if (!scrolledAway)
{
setTitle("Scrolling up");
robot.mouseWheel(-40);
}
else
{
setTitle("Scrolling Down");
robot.mouseWheel(40);
}
scrolledAway = !scrolledAway;
setTitle("Scrolled");
}catch (Exception ex){ex.printStackTrace();}
}
});
timer.setRepeats(true);
timer.start();
getContentPane().add(jsp);
setSize(500,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater( new Runnable()
{
@Override
public void run()
{
MouseScrollRobot msr = new MouseScrollRobot();
msr.createAndShowGUI();
}
});
}
}
回答2:
This works fine for me...
import java.awt.AWTException;
import java.awt.Robot;
public class TestRobotScroll {
public static void main(String[] args) {
try {
Robot bot = new Robot();
bot.setAutoDelay(100);
Thread.sleep(2000);
System.out.println("++");
bot.mouseWheel(25);
Thread.sleep(2000);
System.out.println("--");
bot.mouseWheel(-25);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I had it scroll in the editor and scroll the browser...
来源:https://stackoverflow.com/questions/15714609/robot-class-mousewheel-not-working