我正在尝试创建一个小程序,在屏幕上画一个圆(定义为对象),然后用鼠标在屏幕上拖动这个圆。到目前为止,当按下鼠标时,对象被绘制并可以拖动,但我希望它做的是在小程序启动时绘制对象,然后允许用户单击对象并拖动它。任何帮助或线索都将不胜感激。代码如下:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class sheepDog extends Applet implements ActionListener, MouseListener, MouseMotionListener
{
manAndDog dog;
int xposR;
int yposR;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics g)
{
dog.display(g);
}
public void actionPerformed(ActionEvent ev)
{}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void mouseMoved(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{}
public void mouseDragged(MouseEvent e)
{
dog = new manAndDog(xposR, yposR);
xposR = e.getX();
yposR = e.getY();
repaint();
}
}
class manAndDog implements MouseListener, MouseMotionListener
{
int xpos;
int ypos;
int circleWidth = 30;
int circleHeight = 30;
Boolean mouseClick;
public manAndDog(int x, int y)
{
xpos = x;
ypos = y;
mouseClick = true;
if (!mouseClick){
xpos = 50;
ypos = 50;
}
}
public void display(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(xpos, ypos, circleWidth, circleHeight);
}
public void mousePressed(MouseEvent e)
{
mouseClick = true;
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void mouseMoved(MouseEvent e)
{}
public void mouseClicked(MouseEvent e)
{}
public void mouseDragged(MouseEvent e)
{
if (mouseClick){
xpos = e.getX();
ypos = e.getY();
}
}
}
谢谢
2条答案
按热度按时间uqzxnwby1#
最简单的方法是创建
ManAndDog
在你的init()
方法,类似于:mtb9vblg2#
在
start
方法,为manAndDog
对象和调用repaint
莱默斯说得更对,那init
方法是初始化mananddog的更好地方。希望您不介意一些反馈;)
你应该打电话来
super.paint(g)
在你的paint
方法。事实上,我鼓励你JApplet
和覆盖paintComponent
,但那只是我我认为没有必要不断地重新创建mananddog对象。
例如。如果你添加了一个方法
setLocation
,拖动鼠标时,您只需调用“setlocation”。这是更有效的,因为它不连续创建短暂的对象。这也意味着你可以用
manAndDog
对象,例如应用动画。伊姆霍