2016-10-28 1 views
2

パネルでマウス座標表示を取得しようとしていますが、カーソルを移動するたびにメッセージと新しい座標が前の座標に表示されています。MouseMotionListener JPanelで私は問題を理解することはできません。マウス座標が互いに重なり続ける - Java

enter image description here

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
import java.awt.event.MouseMotionListener; 
public class Main extends JPanel implements MouseMotionListener { 
public JLabel label; 
    public static void main(String[] args) { 
     new Main(); 
     JFrame frame = new JFrame(); 
     frame.setTitle("MouseCoordinates"); 
     frame.setSize(400, 400); 
     frame.addWindowListener(new WindowAdapter() { 
     public void windowClosing(WindowEvent we) { 
     System.exit(0); 
      } 
     }); 
     Container contentPane = frame.getContentPane(); 
     contentPane.add(new Main()); 
     frame.setVisible(true); 
    } 
     public Main() { 
     setSize(400, 400); 
     label = new JLabel("No Mouse Event Captured", JLabel.CENTER); 
     add(label); 
     addMouseMotionListener(this); 
    } 
    public void mouseMoved(MouseEvent e) { 
    label.setText("Mouse Cursor Coordinates => X:" + e.getX() + " |Y:" + e.getY()); 
    } 
    public void mouseDragged(MouseEvent e) {} 
    } 
+0

あなたは私の答えを理解しましたか? – ItamarG3

+0

完全ではありません。 – dkchetan

+0

あなたはjpanelを2回作成していますが、その書き込みは2回表示されます。私の答えをテストし、それが動作するかどうかを確認 – ItamarG3

答えて

1

あなたは二回Mainを作成しています。

public class Main extends JPanel implements MouseMotionListener { 
public JLabel label; 

public static void main(String[] args) { 
    Main m = new Main();// create an object and reference it 
    JFrame frame = new JFrame(); 
    frame.setTitle("MouseCoordinates"); 
    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); 
} 
//... 

あなたの問題は、(JPanelのである)を2回Mainオブジェクトを作成し、次に書き込みが二回登場。 Mainオブジェクトに参照を渡すと、問題は解決されるはずです。

関連する問題