【问题标题】:why is java MouseListener returning the same values x and y values every time I click?为什么每次单击时 java MouseListener 返回相同的值 x 和 y 值?
【发布时间】:2011-11-18 04:20:06
【问题描述】:

我正在创建一个地图编辑器,他们单击的位置将用于向地图添加数据点。

    public MapEditor() throws HeadlessException, FileNotFoundException, XMLStreamException {
    super("MapEditor");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Set JFrame properties.
    this.setTitle("Map Editor");
    this.setSize(PREFERRED_WIDTH, PREFERRED_HEIGHT);
    this.setBackground(Color.gray);

    this.setJMenuBar(makeMenuBar());

    JPanel mainPanel = new JPanel( new BorderLayout());

    Icon image = new ImageIcon("map.jpg");
    JLabel label = new JLabel(image);
    scrollPane = new JScrollPane();
    scrollPane.getViewport().add(label);

    scrollPane.addMouseListener(this);

    mainPanel.add(scrollPane, BorderLayout.CENTER);


    this.getContentPane().add(mainPanel);

    this.getContentPane().add(makeStatusBar(), BorderLayout.SOUTH);

    setVisible(true);
}

当鼠标被点击时,我也有以下事件:

public void mouseClicked(MouseEvent e) {
    int x = getX();
    int y = getY();
    System.out.println("clicked at (" + x + ", " + y + ")");
}

但是,无论我在窗口中的哪个位置单击,它都会返回相同的值。我注意到,如果我将整个窗口移动到屏幕上的其他位置,它会返回不同的值。它们似乎对应于窗口的左上角。我尝试将 MouseListener 添加到不同的组件中,但每个组件都得到相同的结果。一些帮助将不胜感激。

【问题讨论】:

  • getX 和 getY 方法里面有什么?

标签: java swing mouseevent mouselistener


【解决方案1】:

请改用MouseAdapter,因为它是一个用于接收鼠标事件的抽象适配器类。

有关代码示例,请参阅Java MouseListener 接受的答案。

编辑:您没有使用MouseEvent 变量引用,所以getX()getY() 不会返回您所期望的,除非getX()getY() 是您自己的方法?

将代码更改为:

public void mouseClicked(MouseEvent e) {
    int x = e.getX();
    int y = e.getY();
    System.out.println("clicked at (" + x + ", " + y + ")");
}

【讨论】:

    【解决方案2】:

    想通了。它必须是:

    public void mouseClicked(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        System.out.println("clicked at (" + x + ", " + y + ")");
    }
    

    在我刚刚获取窗格的 X 和 Y 之前,而不是鼠标事件发生的位置

    【讨论】:

      猜你喜欢
      • 2019-08-16
      • 1970-01-01
      • 2017-01-09
      • 2013-04-22
      • 2019-12-02
      • 2011-09-28
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多