0

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

PS - 抱歉没有评论...

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);
      }

    }
  }
}
4

2 回答 2

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
}
于 2013-10-09T12:21:16.963 回答
1

您需要正确实现鼠标侦听器。MouesEvent 携带 MouseClick 的位置。

public void mouseClicked(MouseEvent e) {
    System.out.println(e.getPoint().x);
}
于 2013-10-09T12:22:27.490 回答