문제

나는 단순히 이미지를 드래그 할 수있는 애플릿을 만들려고 노력하고 있습니다. 그리고 나는 이미지 개체가 이벤트를 듣기를 원합니다. 여기 스레드에서 간단한 실행되는 애플릿 코드가 있습니다.

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


}

애플릿의 이미지를 볼 수 있지만 이미지를 클릭하거나 클릭하면 아무 일도 일어나지 않습니다. 그래서이 코드에 무슨 문제가 있습니다.

도움이 되었습니까?

해결책

코드 #1의 TAS가 코드 #2에서 움직일 수 있다고 가정하면 ...

실제로 움직일 수있는 것을 구성 요소로 사용하지 않고 대신 애플릿의 그래픽 컨텍스트에 페인트를 칠하도록 요청합니다.

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

대신 애플릿 컨테이너에 움직일 수있는 인스턴스를 추가해야합니다. 여기서 페인팅은 자동화되며 마우스 이벤트를 받기 시작합니다. 또한 그 페인트 () 메소드도 제거 할 수도 있습니다.

다른 팁

우선 당신은 최상위 컨테이너 (Japplet, Jframe, jdialog)의 페인트 방법을 무시해서는 안됩니다.

그런 다음 다른 스윙 구성 요소에서 사용자 정의 그림을 수행하면 Paint () 메소드가 아닌 구성 요소의 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();
        }
    }

}

간단한 대답은 - Mousepressed () 또는 MouserEleident ()에서 아무것도 수행 할 코드가 없다는 것입니다.

코드에는 다른 많은 문제가 있습니다 ...

내가 생각 해낼 수있는 가장 간단한 솔루션 -

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