我需要一些Java代码的帮助。我的代码允许矩形跟随鼠标图标的确切位置,但我想让矩形停在我用鼠标点击绘图面板的位置。如何实现这一目标?谁能帮我?
这是我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Drawing extends JFrame
{
public Drawing()
{}
public static void main(String[] args)
{
Panel p = new Panel();
p.setBackground(Color.white);
JFrame f = new JFrame();
f.setSize(800, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(p);
f.setVisible(true);
f.setLocationRelativeTo(null);
}
}
public class Panel extends JPanel implements MouseMotionListener
{
int x=0;
int y=0;
int width=200;
int height=200;
public Panel()
{
addMouseMotionListener(this);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(x, y, width, height);
}
public void mousePressed(MouseEvent e){}
public void mouseDragged(MouseEvent e){}
public void mouseMoved(MouseEvent e)
{
x = e.getX() - 75;
y = e.getY() -75;
repaint();
}
public void mouseEntered(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseExited(MouseEvent e){}
}
答案 0 :(得分:1)
你的类Panel应该实现MouseListener接口并调用addMouseListener方法才能使用mousePressed方法;要停止移动面板,请使用布尔值,当您按下鼠标按钮时更改状态,将面板类更改为以下代码:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
public class Panel extends JPanel implements MouseMotionListener, MouseListener {
int x = 0;
int y = 0;
int width = 200;
int height = 200;
boolean move = true;
public Panel() {
addMouseMotionListener(this);
addMouseListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (move) {
g.setColor(Color.red);
g.fillRect(x, y, width, height);
}
}
public void mousePressed(MouseEvent e) {
move = !move;
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
if (move) {
x = e.getX() - 75;
y = e.getY() - 75;
repaint();
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}