Reputation: 55
I am developing a coordinate system whereby the points (0,0) will lie in the center of the panel but after translating the default (0,0) coordinates, the mouse coordinates stop displaying.Without this line of code "ga.translate(175.0, 125.0)",the program works .How can I fix this issue?Thanks.
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();
}
}
Upvotes: 2
Views: 167
Reputation: 324108
When you manipulate (certain) values of the Graphics
object (like translates, transforms) you should always restore it to its original state.
An easy way to do this is to create a temporary Graphics
object do to your painting:
@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();
}
Upvotes: 3