具有非活动窗口

时间:2018-04-26 07:01:09

标签: java

如何使用非活动窗口使此MouseListener正常工作?我需要在其他程序中使用机器人键。

我正在使用F7和F8滚动的系统进行编码。我想用鼠标滚动,所以我想制作一个程序,在我向上或向下滚动时听鼠标并发送F7或F8。

public class mouselistener extends JPanel implements MouseWheelListener {
  JTextArea textArea = new JTextArea();

  JScrollPane scrollPane = new JScrollPane(textArea);

  final static String newline = "\n";

  public mouselistener() {

    super(new BorderLayout());
    textArea.setEditable(true);

    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setPreferredSize(new Dimension(400, 250));
    add(scrollPane, BorderLayout.CENTER);


    textArea.addMouseWheelListener(this);

    setPreferredSize(new Dimension(450, 350));
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
  }

  public void mouseWheelMoved(MouseWheelEvent e) {

    Robot robot = null;
    try {
        robot = new Robot();
    } catch (AWTException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    int notches = e.getWheelRotation();
    if (notches < 0) {
      // Simulate a key press
      robot.keyPress(KeyEvent.VK_A); //Later F7
      robot.keyPress(KeyEvent.VK_A);
    } else {
           // Simulate a key press
          robot.keyPress(KeyEvent.VK_B); //Later F8
          robot.keyPress(KeyEvent.VK_B);
    }
  }

  void saySomething(String eventDescription, MouseWheelEvent e) {
    textArea.append(e.getComponent().getClass().getName() + ": " + eventDescription);
    textArea.setCaretPosition(textArea.getDocument().getLength());
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("MouseWheelEventDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JComponent newContentPane = new mouselistener();
    newContentPane.setOpaque(false); // content panes must be opaque
    frame.setContentPane(newContentPane);

    frame.pack();
    frame.setVisible(true);
  }
}

0 个答案:

没有答案
相关问题