2016-10-29 14 views
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(); 

    } 

} 

回答

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(); 
} 
+0

代碼工作,但鼠標的座標在面板的左上角顯示(0,0),但我需要鼠標座標在翻譯後的點(175.0,125.0)顯示(0,0)。 – dkchetan

+0

@dkchetan,是的繪畫方法中的翻譯不會影響MouseEvent的實際鼠標座標。您需要手動轉換Mouse事件中的Point。所以基本上我不明白這個要求的基本原理。它增加了所有鼠標處理邏輯的開銷。 – camickr