鼠标单击坐标不起作用

时间:2013-10-09 12:17:51

标签: java swing click mouse mouselistener

我有一个程序,目前我试图在点击时找到面板上的坐标位置。到目前为止,我现在得到0,0。有什么建议吗?

P.S - 对于缺乏评论感到抱歉......

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.lang.Math;

public class ShapePanel extends JPanel{

  private JButton startButton, stopButton;
  private JTextField textField;
  private JLabel label;
  private Timer timer;
  private final int DELAY = 5;


  ArrayList<Shape> obj = new ArrayList<Shape>();


  public static void main(String[] args){

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new ShapePanel());
    frame.pack();
    frame.setVisible(true);
  }

  public ShapePanel(){

    DrawingPanel dpanel = new DrawingPanel();
    JPanel cpanel = new JPanel();

    startButton = new JButton("Start");
    stopButton = new JButton("Stop");

    cpanel.setLayout(new GridLayout(2,1));
    cpanel.add(startButton);
    cpanel.add(stopButton);


    dpanel.addMouseListener(new MouseListen());

    TimerListener tListen = new TimerListener();

    startButton.addActionListener(tListen);
    stopButton.addActionListener(tListen);
    add(cpanel);
    add(dpanel);

    timer = new Timer(DELAY, tListen);
    timer.start();

  }
  private class TimerListener implements ActionListener{


    public void actionPerformed(ActionEvent e){

      if (e.getSource() == timer){

        for (int i = 0; i < obj.size(); i++){
          obj.get(i).move();
        }

      }else if (e.getSource() == startButton){

        timer.start();
      }else if (e.getSource() == stopButton){

        timer.stop();
      }


      repaint();
    }
  }

  private class MouseListen implements MouseListener {


    public void mousePressed(MouseEvent e) {
    }

    public void mouseReleased(MouseEvent e) {

    }

    public void mouseEntered(MouseEvent e) {

    }

    public void mouseExited(MouseEvent e) {

    }

    public void mouseClicked(MouseEvent e) {


      System.out.println(getX());
    }

}

  private class DrawingPanel extends JPanel{

    DrawingPanel(){

      setPreferredSize(new Dimension(400,400));
      setBackground(Color.pink);

    }
    public void paintComponent(Graphics g){
      super.paintComponent(g);
      for(int i = 0; i < obj.size(); i++){

        obj.get(i).display(g);
      }

    }
  }
}

2 个答案:

答案 0 :(得分:4)

检查代码的以下部分:

public void mouseClicked(MouseEvent e) {


  System.out.println(getX());  
       // you are putting here only getX() which get the postion of panel
        // put e.getX() instead
}

答案 1 :(得分:1)

您需要正确实现mouselistener。 MouesEvent带有MouseClick的位置。

public void mouseClicked(MouseEvent e) {
    System.out.println(e.getPoint().x);
}