2010-06-18 22 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); 
       } 
      }); 
     } 
    } 
相關問題