【问题标题】:Adding mouseListener to my object in java在java中将mouseListener添加到我的对象
【发布时间】:2009-07-15 15:29:09
【问题描述】:

我正在尝试制作一个可以简单地拖动图像的小程序。我希望图像对象能够监听事件。所以这里是在一个线程中简单运行的小程序代码:

import java.awt.*;
import java.net.URL;
import javax.swing.JApplet;

public class Client extends JApplet implements Runnable {
    private static final long serialVersionUID = 1L;
    MediaTracker mediaTracker;
    Image [] imgArray;
    Tas t1;

    public void init() 
    { 
        mediaTracker = new MediaTracker(this);
        imgArray = new Image[1];

        URL base = getCodeBase(); 
        imgArray[0] = getImage(base,"okey.png");
        mediaTracker.addImage(imgArray[0],1);

        try {
            mediaTracker.waitForAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t1 = new Tas(this, new Rectangle(0, 0, imgArray[0].getWidth(this), imgArray[0].getHeight(this)), imgArray[0]);

        Thread t = new Thread(this);
        t.start();
    }

    public void paint(Graphics g) 
    {
        t1.paint(g);
    }

    @Override
    public void run() {
        while(true){
            //System.out.println("run");
            repaint();
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

保存图像的对象类别是:

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Movable extends JPanel implements MouseListener {

public Client mainObj;
public Rectangle rect;
public Image image;

public Movable(Client mainObj, Rectangle rect, Image image) {
    this.mainObj = mainObj;
    this.rect = rect;
    this.image = image;
    addMouseListener(this);
}

public void paint(Graphics g) {
    g.drawImage(image, rect.x, rect.y, rect.width, rect.height, this);
}

@Override
public void mouseClicked(MouseEvent arg0) {
    System.out.println("clicked");
}

@Override
public void mouseEntered(MouseEvent arg0) {

}

@Override
public void mouseExited(MouseEvent arg0) {

}

@Override
public void mousePressed(MouseEvent arg0) {
    System.out.println("pressed");
}

@Override
public void mouseReleased(MouseEvent arg0) {

}
}

@SuppressWarnings("serial")
class Tas extends Movable{
    public String name = "";

    public Tas(Client mainObj, Rectangle rect, Image image) {
        super(mainObj, rect, image);
    }


}

我可以在我的小程序中看到该图像,但是当我点击进入或退出该图像时没有任何反应。那么这段代码有什么问题。

【问题讨论】:

    标签: java applet mouse listener


    【解决方案1】:

    假设代码 #1 中的 Tas 在代码 #2 中是可移动的...

    您实际上并没有将 Moveable 用作组件,而是要求它将自己绘制到 Applet 的图形上下文中,这里:

    public void paint(Graphics g) 
    {
        t1.paint(g);
    }
    

    相反,您应该将 Moveable 的实例添加到 Applet 的容器中,其中绘画将变为自动,并且它将开始接收鼠标事件。您也可以删除该 paint() 方法。

    【讨论】:

      【解决方案2】:

      首先,您不应该覆盖顶级容器(JApplet、JFrame、JDialog)的绘制方法。

      然后要在其他 Swing 组件上进行自定义绘制,您需要覆盖组件的 paintComponent() 方法,而不是 paint() 方法。阅读 Custom Painting 上的 Swing 教程。所以首先解决这些问题。

      我不确定线程​​的意义是什么,但在您解决其他问题之前将其从您的代码中删除。如果您尝试制作动画,那么您应该使用Swing Timer,而不是线程。

      如果您想查看一些用于拖动组件的代码,您可以查看Moving Windows 以获得一些通用代码。

      【讨论】:

        【解决方案3】:

        这是一个可行的解决方案。它不是一个小程序,但您可以轻松地转换它。希望对您有所帮助:

        import java.awt.Color;
        import java.awt.Dimension;
        import java.awt.Graphics;
        import java.awt.Image;
        import java.awt.event.MouseAdapter;
        import java.awt.event.MouseEvent;
        import java.awt.event.MouseMotionAdapter;
        import java.awt.geom.Point2D;
        import java.io.File;
        import java.io.IOException;
        
        import javax.imageio.ImageIO;
        import javax.swing.JFrame;
        import javax.swing.JPanel;
        
        @SuppressWarnings("serial")
        public class ImagePanel extends JPanel {
        
            Image image;
            Point2D axis = new Point2D.Double();
            boolean drag = false;
            Point2D dragPoint = new Point2D.Double();
        
            public ImagePanel(Image image) {
                this.image = image;
                setPreferredSize(new Dimension(300,300));
                addMouseListener(new MouseAdapter() {
                    @Override
                    public void mousePressed(MouseEvent e) {
                        drag = true;
                        dragPoint = e.getPoint();
                    }
        
                    @Override
                    public void mouseReleased(MouseEvent e) {
                        drag = false;
                    }
                });
                addMouseMotionListener(new MouseMotionAdapter() {
                    @Override
                    public void mouseDragged(MouseEvent e) {
                        if (drag) {
                            axis.setLocation(axis.getX()
                                    + (e.getPoint().x - dragPoint.getX()), axis.getY()
                                    + (e.getPoint().y - dragPoint.getY()));
                            dragPoint = e.getPoint();
                            repaint();
                        }
                    }
                });
            }
        
            @Override
            public void paintComponent(Graphics g) {
                g.setColor(Color.white);
                g.fillRect(0, 0, getWidth(), getHeight());
                g.drawImage(image, (int) axis.getX(), (int) axis.getY(), null);
            }
        
            public static void main(String[] args) {
                try {
                    JFrame f = new JFrame();
                    f.getContentPane().add(
                            new ImagePanel(ImageIO.read(new File("image.jpg"))));
                    f.pack();
                    f.setVisible(true);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        
        }
        

        【讨论】:

          【解决方案4】:

          简单的答案是 - 您没有代码可以在 mousePressed() 或 mouseReleased() 中执行任何操作。

          虽然代码中还有很多其他问题...

          我能想到的最简单的解决方案 -

          public class Client extends JApplet {
          
          private MouseInputAdapter myMouseListener = new MyMouseListener();
          
          public void init() {
              // usually a very bad idea, but needed here 
              // since you want to move things around manually
              setLayout(null);
          
              // assuming this will get used often, so making it a method.
              addLabelForImage(getImage(getCodeBase(), "okay.png"));
          }
          
          private void addLabelForImage(Image image) {
              ImageIcon icon = new ImageIcon(image);
              JLabel l = new JLabel(icon);
              add(l);
              l.setSize(l.getPreferredSize());
              // you'll probably want some way to calculate initial position 
              // of each label based on number of images, size of images, 
              // size of applet, etc. - just defaulting to 100,100 now.
              l.setLocation(100, 100);
              l.addMouseListener(myMouseListener);
              l.addMouseMotionListener(myMouseListener);
          }
          
          // Made this a MouseInputAdapter because I assume you may want to handle
          // other types of mouse events later...
          private static class MyMouseListener extends MouseInputAdapter {
              @Override
              public void mouseDragged(MouseEvent e) {
                  // when the mouse is dragged over a the component this listener is
                  // attached to (ie - one of the labels) convert the point of the mouse
                  // event from the internal component coordinates (0,0 is upper right 
                  // corner of each label), to it's parent's coordinates (0,0 is upper
                  // right corner of the applet), and set the components location to 
                  // that point.
                  Component theLabel = e.getComponent();
                  Container theApplet = theLabel.getParent();
                  Point labelPoint = e.getPoint();
                  Point appletPoint = SwingUtilities.convertPoint(
                          theLabel, labelPoint, theApplet );
                  theLabel.setLocation(appletPoint);
              }
          }
          
          }
          

          【讨论】:

            猜你喜欢
            • 2018-02-19
            • 1970-01-01
            • 2015-02-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-10-29
            • 2015-09-04
            • 2013-06-29
            相关资源
            最近更新 更多