javaswingjpanelimageiconmouse-listeners

Java - change JPanel image with mouse


I am trying to create a panel with pictures that are changed with the mouse. I have 10 images (0.png to 9.png). My problem is, I want to move image and I am currently viewing the second picture. I used the JScrollPane to scroll back to the first image, but only the first image is moving. How can I refresh my panel and be able to move all images?

This is my code:

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.*;

class MapFrame extends JPanel {
    /**
     * 
     */
    private static final long serialVersionUID = (long) 1.0;
    private static Image image;
    private static JLabel label = new JLabel();
    private static int ind =0;
    private static JFrame frame;
    private static String str;
   //----------------------------------------------------------------- 
    public MapFrame(){      }

   //----------------------------------------------------------------- 

    public MapFrame(String pathe) {
        super(new BorderLayout());
          image = new ImageIcon(getClass().getResource(pathe)).getImage();
          label = new JLabel(new ImageIcon(image));  
          JScrollPane scroll = new JScrollPane(label,JScrollPane.VERTICAL_SCROLLBAR_NEVER,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
          add(scroll);

          HandLcalss hand = new HandLcalss(label);
          JViewport v = scroll.getViewport();
          v.addMouseListener(hand);
          v.addMouseMotionListener(hand);
          v.addMouseWheelListener(hand);
    }

   //----------------------------------------------------------------- 


    public static void ShowGUI(String pathe) {
        frame = new JFrame("Bladi_map");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(new MapFrame(pathe));
        frame.setSize(500,400);  
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

   //----------------------------------------------------------------- 

    public static void ChangImage(String pathe){
        frame.getContentPane().add(new MapFrame(pathe));        
        label.revalidate();
        frame.setVisible(true);     
    }

    //----------------------------------------------------------------- 
class HandLcalss implements MouseListener,MouseMotionListener,MouseWheelListener{
    private static final int DELAY = 10;
    private  Cursor hc = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
    private  Timer scroller;
    private  JComponent label;
    private  Point startPt = new Point();
    private  Point move    = new Point();
    //----------------------------------------------------------------- 
    public HandLcalss(JComponent comp) {
        this.label = comp;
        comp.getCursor();
        this.scroller = new Timer(DELAY, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {               
            }
        });
    }
    //----------------------------------------------------------------- 

    @Override public void mouseDragged(MouseEvent e) {
        JViewport vport = (JViewport)e.getSource();
        Point pt = e.getPoint();
        int dx = startPt.x - pt.x;
        int dy = startPt.y - pt.y;
        Point vp = vport.getViewPosition();
        vp.translate(dx, dy);
        label.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
        startPt.setLocation(pt);
    }
    @Override
    public void mousePressed(MouseEvent e) {
        ((JComponent)e.getSource()).setCursor(hc);
        startPt.setLocation(e.getPoint());
        move.setLocation(0, 0);
        scroller.stop();
    }
    @Override
    public void mouseWheelMoved(MouseWheelEvent e) {
        int notches = e.getWheelRotation();

        if (notches < 0) {
            ind++;
            if(ind <0){ind=0;}
            if(ind<=9){
            str="/resources/"+ind+".png";       
             ChangImage(str);
            System.out.println("indink"+str);
            }
        } else {
            ind--;
            if(ind >9){ind=8;}
            if(ind>=0){
            str="/resources/"+ind+".png";
            ChangImage(str);
            System.out.println("ind"+ind);
            }             
        }   
      }
    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub          
    }

    @Override
    public void mouseMoved(MouseEvent arg0) {
        // TODO Auto-generated method stub
    }
    @Override
    public void mouseEntered(MouseEvent arg0) {
        // TODO Auto-generated method stub      
    }
    @Override
    public void mouseExited(MouseEvent arg0) {
        // TODO Auto-generated method stub      
    }
    @Override
    public void mouseReleased(MouseEvent arg0) {
        // TODO Auto-generated method stub      
    }
}

//----------------------------------------------------------------- 
}

This is the main class:

public class main { 
    public static void main(String[] args) {
        MapFrame.ShowGUI("/resources/0.png");       
    }
}

Solution

  • You have 2 problems in your code:

    The first:

    public static void ChangImage(String pathe){
        frame.getContentPane().add(new MapFrame(pathe));        
        label.revalidate();
        frame.setVisible(true);     
    } 
    

    When you change image (invoked on mouse wheel event) you simply add new panel (MapFrame) with image to existing container: (Container pane = frame.getContentPane()). The old ones are still there and are overlapping with the new panel. The above method should be:

    public static void ChangImage(String pathe) {
        frame.getContentPane().removeAll();
        frame.getContentPane().add(new MapFrame(pathe));
        label.revalidate();
        frame.setVisible(true);
    }
    

    The second thing:

    Why complicate? (also there is an error on 0 value of ind):

    @Override
        public void mouseWheelMoved(MouseWheelEvent e) {
            int notches = e.getWheelRotation() * -1;
            ind += notches;
            if(ind < 0) {
                ind = 0;
            }
            else if(ind > 9) {
                ind = 9;
            }
            str = "/resources/" + ind + ".png";
            ChangImage(str);
        }
    

    And the last thing:

    If you are implementing all mouse interfaces - you can extend MouseAdapter. Now you needn't override methods you don't want.