我有这个代码,它创建了一个简单的笑脸。我想用鼠标移动来移动脸部的眼睛。这是代码
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);
}
答案 0 :(得分:1)
您需要实现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();
}
});
}
}