2010-06-18 47 views
1

我想问另一个问题:如何处理Windows中的Java事件。具体而言,我想知道如何处理在Windows XP和Vista中鼠标移动或鼠标点击等事件。我想将自己的自定义行为连接到这些事件,即使我的应用程序处于非活动状态或隐藏状态。如何在JAVA中处理Windows XP或VISTA事件

所有帮助表示赞赏!

回答

1

您可以添加例如通过调用

addMouseListener() 

一个MouseListener的任何JComponent中有你可以用它来代替MouseListeners

  • 不同的事件侦听器的KeyListener
  • 的WindowListener
  • 的ComponentListener
  • 的ContainerListener
  • 的FocusListener
  • ...还有更多

检查here for an detailed explanation

可以完全实现MouseListener接口或只使用convienience类MouseAdapter,其中有方法存根,所以你不要有实现每个单独的方法。

检查此示例:

public class MyFrame extends JFrame { 
    private MouseListener myMouseListener; 

     public MyFrame() { 
      this.setSize(300, 200); 
      this.setLocationRelativeTo(null); 
      // create the MouseListener... 
      myMouseListener = new MouseAdapter() { 
       @Override 
       public void mouseClicked(MouseEvent e) { 
        System.out.println("clicked button " + e.getButton() + " on " + e.getX() + "x" + e.getY()); // this gets called when the mouse is clicked. 
       } 
      }; 
      // register the MouseListener with this JFrame 
      this.addMouseListener(myMouseListener); 
     } 

     public static void main(String[] args) { 
      SwingUtilities.invokeLater(new Runnable() { 
       @Override 
       public void run() { 
        MyFrame frame=new MyFrame(); 
        frame.setVisible(true); 
       } 
      }); 
     } 
    }