想用鼠标画个点,可以坐标总是不对,不知道要怎么改。
- Java code
import javax.swing.*;import java.awt.*;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;public class DrawTest extends JFrame { MyPanel mp = null; public static void main(String[] args) { new DrawTest(); } public DrawTest() { mp = new MyPanel(); this.addMouseListener(mp); this.add(mp); this.setSize(600, 400); this.setLocation(400, 300); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); }}class MyPanel extends JPanel implements MouseListener { int x = 0, y = 0; Image img = null; public void paint(Graphics g) { super.paint(g); g.fillOval(x, y, 10, 10); } public void mouseClicked(MouseEvent e) { x = e.getX(); y = e.getY(); this.repaint(); } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { }}
------解决方案--------------------------------------------------------
- Java code
import javax.swing.*;import java.awt.*;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;public class DrawTest extends JFrame { MyPanel mp = null; public static void main(String[] args) { new DrawTest(); } public DrawTest() { mp = new MyPanel(); // 鼠标事件是加在frame上,而不是在mp上的, // 所以在mp中取得坐标时,坐标不是相对于mp的,而是相对于frame的 // 而frame还有一个标题栏,这个是有高度的 // 最终使用屏幕坐标转换成组件坐标可以解决这一问题 this.addMouseListener(mp); this.add(mp); this.setSize(600, 400); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); }}class MyPanel extends JPanel implements MouseListener { int x = 0, y = 0; Image img = null; @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.fillOval(x, y, 10, 10); } public void mouseClicked(MouseEvent e) { Point p = e.getLocationOnScreen(); SwingUtilities.convertPointFromScreen(p, this); // 关键在于把屏幕坐标映射成组件坐标 x = p.x; y = p.y; this.repaint(); } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { }}