سؤال

أحاول إنشاء برنامج صفيح يمكنني ببساطة سحب صورة. وأريد كائن صورة للاستماع إلى الأحداث. لذلك هنا هو رمز التطبيق الصغير الذي تشغيل بسيط في مؤشر ترابط:

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);
    }


}

أستطيع أن أرى الصورة في برنامج التبريد الخاص بي ولكن لا شيء يحدث عند النقر فوق الصورة أو الخروج منها. إذن ما هو الخطأ في هذا الرمز.

هل كانت مفيدة؟

المحلول

على افتراض أن TAS في Code # 1 هو المنقولة في الكود # 2 ...

أنت لا تستخدم بالفعل المنقولة كمكون كمكون، ولكن بدلا من ذلك اطلب منه رسم نفسه على سياق رسومات التطبيق الصغير هنا:

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

بدلا من ذلك، يجب عليك إضافة مثيل من جديد على حاوية التطبيق الصغير، حيث ستصبح اللوحة تلقائيا، وستبدأ في تلقي أحداث الماوس. يمكنك أيضا إزالة طريقة الطلاء () ثم أيضا.

نصائح أخرى

بادئ ذي بدء، لا ينبغي أبدا تجاوز طريقة الطلاء لحاوية المستوى الأعلى (Japplet، JFrame، Jdialog).

ثم للقيام اللوحة المخصصة على مكونات التأرجح الأخرى التي تتجاوز طريقة PaintComponent () المكون، وليس طريقة الطلاء (). اقرأ البرنامج التعليمي اللوحة المخصصة. وبعد لذلك أولا إصلاح تلك المشاكل.

لست متأكدا من أن نقطة الخيط ليست سوى إزالته من التعليمات البرمجية حتى تحل مشاكلك الأخرى. إذا كنت تحاول القيام بالرسوم المتحركة، فيجب عليك استخدام تأرجح الموقت, وليس موضوع.

إذا كنت ترغب في رؤية بعض التعليمات البرمجية لسحب المكونات، فيمكنك إلقاء نظرة على نقل ويندوز لبعض الكود العام.

هذا حل عمل. إنه ليس تطبيق صغير ولكن يمكنك بسهولة تحويل ذلك. آمل أن يساعد:

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();
        }
    }

}

الجواب البسيط هو - ليس لديك رمز لفعل أي شيء في المولون () أو mousereladed ().

هناك الكثير من المشاكل الأخرى في التعليمات البرمجية على الرغم من ...

أبسط حل يمكن أن يأتي مع -

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);
    }
}

}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top