gpt4 book ai didi

java - 如何在java中通过鼠标移动来移动形状

转载 作者:行者123 更新时间:2023-12-01 10:01:49 27 4
gpt4 key购买 nike

我有这段代码,它创建了一个简单的笑脸。我想通过鼠标移动来移动脸部的眼睛。这是代码

int a,b;
public void recieve(int x,int y)
{
a=x;
b=y;
System.out.println("xaxis"+a+"yaxis"+b);
}

@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
System.out.println("x axis: "+a+" -- y axis: "+b);
g.drawArc(100, 50, 150, 150, 0, 360);
g.drawArc(125, 65, 40, 40, 0, 360);
g.drawArc(180, 65, 40, 40, 0, 360);
g.drawArc(165, 105, 15, 15, 60, 180);


g.fillOval(a-130, 70, 15, 15);
g.fillOval(b-185, 70, 15, 15);
}

最佳答案

您需要实现 MouseMotionListener 并将其附加到您的paintComponent() 方法所在的任何 JPanel 子类。在其方法中,修改“a”和“b”变量的值。

下面是一个例子。从你的问题中我不清楚你希望眼睛做什么类型的运动 - 例如瞳孔是否应该始终“看着”鼠标指针而不离开眼睛 - 例如从左眼鼠标指针的 x 坐标中减去 x 的起始值,并从左眼的 y 坐标中减去 x 的起始值正如您的代码片段所示,右眼的鼠标指针并没有真正产生有意义的结果。

因此,在下面的演示中,眼睛只是跟踪鼠标指针。它向您展示了如何拾取鼠标移动事件并获取鼠标的 X 和 Y 坐标 - 如何使用这些坐标以您想要的任何方式调整瞳孔的位置取决于您,并且(希望如此)现在只是一个数学问题。

import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

public class MouseTrackingSmilieFace extends JFrame {

private int a;
private int b;

private JPanel smilieFacePanel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawArc(100, 50, 150, 150, 0, 360);
g.drawArc(125, 65, 40, 40, 0, 360);
g.drawArc(180, 65, 40, 40, 0, 360);
g.drawArc(165, 105, 15, 15, 60, 180);
g.fillOval(a, b, 15, 15);
g.fillOval(a+55, b, 15, 15);
// Register the motion listener
addMouseMotionListener(new MouseMotionListener() {

// Do the same thing whether the mouse button is depressed...
public void mouseDragged(MouseEvent e) {
processMovement(e);
}

// ... or not.
public void mouseMoved(MouseEvent e) {
processMovement(e);
}

/* Process the movement by capturing the x coordinate of the mouse in member variable 'a'
* and the y coordinate in member variable 'b'.
*/
private void processMovement(MouseEvent e) {
a = e.getX();
b = e.getY();
System.out.println("X = " + a + " Y = " + b);
smilieFacePanel.repaint();
}
});
}
};

private MouseTrackingSmilieFace() {
// Invoke the JFrame superclass constructor and configure the frame
super("Mouse-tracking smilie face");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400,400);
this.setVisible(true);
// Add a panel to the frame and draw the face within it.
this.add(smilieFacePanel);
}

public static void main(String[] args) {
// Create on the Event Dispatch Thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MouseTrackingSmilieFace();
}
});
}
}

关于java - 如何在java中通过鼠标移动来移动形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36755610/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com