![](/img/trans.png)
[英]I want to get coordinates of x and y using mouse adapter and insert into an array. But only two values are getting updated every time in whole array
[英]why is java MouseListener returning the same values x and y values every time I click?
我正在創建一個地圖編輯器,單擊它們的位置將用於向地圖添加數據點。
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添加到不同的組件中,但是每個組件都得到相同的結果。 一些幫助將不勝感激。
請改用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 + ")");
}
弄清楚了。 它必須是:
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("clicked at (" + x + ", " + y + ")");
}
在我只獲取窗格的X和Y之前,而不是鼠標事件發生的位置
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.