当图像移动时,图像上的对象不会移动 [英] Object on Image does not move when Image moves

查看:79
本文介绍了当图像移动时,图像上的对象不会移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两节课.第一个JPanelImageImage添加到我的JPanel中.第二个myObjet代表我要在Image上添加的对象. Image可以移动并可以缩放.

I have two classes. The first, JPanelImage, adds an Image to my JPanel. The second, myObjet, represents the object I want to add on my Image. The Image can move and can zoom.

问题是当我移动图像时,对象保持固定.

The problem is that when I move the image, the object remains fixed.

Class JImagePanel:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Panel;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

class JImagePanel extends Panel{
    private static final long serialVersionUID = 5375994938523354306L;
    private  MediaTracker tracker;
    private Image img;
    private Dimension imgSize,iniSize;
    private int zoom = 0 ;
    private int MouseX;
    private int MouseY;
    int transX=0;
    int transY=0;

    public JImagePanel(String file){
        //setSize(100,200);
        img=Toolkit.getDefaultToolkit().getImage(file);
    setLayout(null);
        tracker=new MediaTracker(this);

        tracker.addImage(img,0);

        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                MouseX = e.getX();
                MouseY = e.getY();
            }
        });

        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                transX += e.getX()-MouseX;
                transY += e.getY()-MouseY;
                MouseX = e.getX();
                MouseY = e.getY();

                repaint();
            }
        });

        try{
            tracker.waitForAll();
        }
        catch(Exception ie){}
        imgSize=iniSize=new Dimension(img.getWidth(this),img.getHeight(this));
    }

    public Dimension getPreferredSize(){
        return new Dimension(imgSize);
    }

    public void paint(Graphics g){
        super.paint(g);
        if(imgSize.width<=iniSize.width) {
            imgSize=iniSize; 
        }

        g.drawImage(this.img, (getWidth()-imgSize.width)/2+transX, (getHeight()-imgSize.height)/2+transY, imgSize.width,imgSize.height,this);
    }
    public void zoomIn(){
        int x=10*imgSize.width/100; 
        int y=10*imgSize.height/100;
        imgSize=new Dimension(imgSize.width+x,imgSize.height+y); 
        if(imgSize.width>iniSize.width){
            setSize(imgSize);
            getParent().doLayout();
        }
        repaint();
    }
    public void zoomOut(){
        int x=10*imgSize.width/100;
        int y=10*imgSize.height/100;
        imgSize=new Dimension(imgSize.width-x,imgSize.height-y);
        if(getWidth()>iniSize.width)
        {
            setSize(imgSize);
            getParent().doLayout();

        }
        repaint();
    }

    public int getZoom() {
        return zoom;
    }

Class myObjet:

import java.awt.BorderLayout;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class myObjet extends JPanel {

    JLabel lblName,lblAct,lblSeuil ;
    JPanel panelObjet;

    public myObjet(String NameObjet ,double activite  )
    {
        ImageIcon img = createImageIcon("images/Source.png");
        lblName = new JLabel(img);
        lblAct = new JLabel(String.valueOf(activite));
        panelObjet = new JPanel();
        panelObjet.setToolTipText(NameObjet);
        panelObjet.setLayout(new BorderLayout());
        panelObjet.add("North",lblName);
        panelObjet.add("South",lblAct);
       add(panelObjet);
       isOpaque();
    }

    public ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = getClass().getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            JOptionPane.showMessageDialog(null, "Cette image n'existe pas : " + path, "Erreur", JOptionPane.ERROR_MESSAGE);
            //  System.err.println("L'image n'est pas dans : " + path);
            return null;
        }
    }
    public boolean isOpaque()
    {
        return true ; 
    }
}


MYObject一个人,我将此对象添加到此Image的面板中.


MYObject is alone , i adds this Object in Panel of this Image .

这是我如何使用这些类的具体示例

Here is a concrete example of how I use these classes

public static void (String [] args )
   {
imagePanel = new JImagePanel("/home/Image.png");
p = new JPanel();
        p.setLayout(new FlowLayout());
     //   p.setBounds(0,0,0,0);
        p.add(getImagePanel());
        ple2.add("Center",p);

}

2/in actionPerformed:

2/ in actionPerformed :

public void actionPerformed(ActionEvent ev) {



    Object sourceEv = ev.getSource() ; 




    if(sourceEv == action.jpfI.btnFrame[4])
    {   
        df =  new DecimalFormat("0.00");


        int x = Integer.valueOf(action.jpfI.lblTxt[4].getText());
        int y =Integer.valueOf(action.jpfI.lblTxt[5].getText()) ;
        x =(int)(x/0.26) ;
        y =(int)(y/0.26):


        objet = new myObjet("islem","0.002");
        objet.setBounds(x,y , 50,50);


        action.getImagePanel().addImage(objet);
        action.repaint();

    }

推荐答案

好的,我遇到了三个问题.

Okay, I've come across three issues.

首先:图像窗格上没有布局管理器.没什么大不了的,但是如果您不打算使用布局管理器,则您有责任对所有子组件进行布局.我通过将以下内容添加到"myObjet"类中来修复了该错误(错误的位置).

Firstly: There's no layout manager on the image pane. No big deal, but if you're not going to use a layout manager, you become responsible for laying out any child components. I fixed this (and it's in the wrong place) by adding the following to the "myObjet" class.

Dimension size = getPreferredSize();
setBounds(0, 0, size.width, size.height);

JImagePanel实际上应该解决这个问题-添加布局管理器或检查doLayout方法.

This really should be taken care of by the JImagePanel - either add a layout manager or check the doLayout method.

其次:JImagePanel是一个重量级的组件.如果可能的话,应避免混合重组分和轻组分(除其他外,还有Z顺序问题).我更新了JImagePanel以从JPanel扩展.

Secondly: The JImagePanel is a heavy weight component. You should avoid mixing heavy and light weight components if you can (there are Z order issues amongst other things). I updated the JImagePanel to extend from a JPanel.

第三,您应该很少需要重写paint方法.在您的情况下,我可以理解您为什么这样做,但是最终要做的是在所有其他事物的顶部进行绘画(并与您正在使用较重的分量的事实混合在一起,使问题更加复杂).

Thridly: You should only very rarely have to override the paint method. In your case I can understand why you did, but what you ended up doing was painting on the top of everything else (and mixed with the fact you were using a heavy weight component compounded the issue).

我将"paint"更改为"paintComponent",以绘制背景并能够使其正常工作.我能够四处移动图像,并将"myObjet"可见并固定在适当的位置.

I changed the "paint" for "paintComponent" which paints the background and was able to get it to work nicely. I was able to move the image around and have the "myObjet" visible and static in place.

更新

好吧...

        public void mouseDragged(MouseEvent e) {
            transX += e.getX() - MouseX;
            transY += e.getY() - MouseY;
            MouseX = e.getX();
            MouseY = e.getY();

            // Add this to your code
            for (Component comp : getComponents()) {

                comp.setLocation(transX, transY);

            }

            repaint();
        }

实际上,更好的解决方案是允许父容器处理移动并在图像窗格中静态设置图像和对象(我的窗格设置为静态大小).您在这里运行的基本思想只需要移到容器中即可.

In fact, a better solution would be to allow the parent container to handle the movement and set the image and objects statically with in the image pane (my pane was set to a static size). The basic idea you have running here just needs to be moved to the container.

您需要处理的唯一另一件事是窗格的Z顺序.

The only other thing you would need to deal with is the Z order of the panes.

这篇关于当图像移动时,图像上的对象不会移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆