1
我正在開發一個座標系,點(0,0)將位於面板的中心,但在翻譯默認(0,0)座標後,鼠標座標停止顯示。如果沒有這行代碼「ga.translate(175.0,125.0)」,該程序將工作。如何解決此問題?謝謝。鼠標座標停止工作後,使用翻譯recallibrate協調系統-java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.MouseMotionListener;
import javax.swing.JLabel;
public class Main extends JPanel implements MouseMotionListener {
public JLabel label;
//@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D ga = (Graphics2D) g;
ga.translate(175.0, 125.0); //the mouse coordinates stop displaying with this code
ga.drawLine(0, 0, 100, 100);
}
public static void main(String[] args) {
Main m = new Main();
GraphicsDraw D = new GraphicsDraw();
JFrame frame = new JFrame();
frame.setTitle("MouseCoordinates111");
frame.setSize(400, 400);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(m);
frame.setVisible(true);
}
public Main() {
setSize(400, 400);
label = new JLabel("No Mouse Event Captured", JLabel.CENTER);
add(label);
//super();
addMouseMotionListener(this);
}
@Override
public void mouseMoved(MouseEvent e) {
//System.out.println(e.getX() + "/" + e.getY());
label.setText("Mouse Cursor Coordinates => X:" + e.getX() + " |Y:" + e.getY());
}
@Override
public void mouseDragged(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
}
}
代碼工作,但鼠標的座標在面板的左上角顯示(0,0),但我需要鼠標座標在翻譯後的點(175.0,125.0)顯示(0,0)。 – dkchetan
@dkchetan,是的繪畫方法中的翻譯不會影響MouseEvent的實際鼠標座標。您需要手動轉換Mouse事件中的Point。所以基本上我不明白這個要求的基本原理。它增加了所有鼠標處理邏輯的開銷。 – camickr