我正在开发一个坐标系,其中点(0,0)将位于面板的中心,但在翻译默认(0,0)坐标后,鼠标坐标停止显示。没有这行代码“ga .translate(175.0,125.0)“,该程序有效。我如何解决这个问题?谢谢。
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 :(得分:3)
当您操纵Graphics
对象的某些值(如翻译,变换)时,您应该始终将其恢复到原始状态。
一种简单的方法是为您的绘画创建一个临时的Graphics
对象:
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
//Graphics2D ga = (Graphics2D) g;
Graphics2D ga = (Graphics2D)g.create();
ga.translate(175.0, 125.0); //the mouse coordinates stop displaying with this code
ga.drawLine(0, 0, 100, 100);
ga.dispose();
}