我想问另一个问题,如何用Java处理Windows的事件。具体来说,我想知道如何在Windows XP和Vista中处理鼠标移动或鼠标单击等事件。我想将我的应用程序中的自定义行为连接到这些事件,即使我的应用程序处于非 Activity 状态或以其他方式隐藏。
感谢所有帮助!
最佳答案
您可以添加例如通过调用任何 JComponent 的 MouseListener
addMouseListener()
您可以使用不同的事件监听器来代替鼠标监听器
- 按键监听器
- 窗口监听器
- 组件监听器
- 容器监听器
- 焦点监听器
- ...还有更多
检查here for an detailed explanation
您可以完全实现 MouseListener 接口(interface),或者只使用方便的 MouseAdapter 类,它具有方法 stub ,因此您不必实现每个方法。
检查此示例:
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);
}
});
}
}
关于java - 如何在JAVA中处理Windows XP或VISTA事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3067562/