Question

I want to get the solution for a Java program. I want to change the image in a rectangular box as soon as the mouse cursor hovers over the box. The images in the box has to keep on changing (at least 5 different images) till the mouse is on the images and stop changing as the cursor goes out of the box.I want to set the images using only the g.drawImage(), where g is a Graphics2D object.

Please help me figure out this problem as i am stuck.

Was it helpful?

Solution 3

This code may help you some!

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class answer {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public answer(){
        JFrame frame=new JFrame();
        frame.getContentPane().add(new rectangle());
        frame.pack();
        frame.setVisible(true);

    }
    public static void main(String args[]){
        new answer();
    }

    public class rectangle extends JPanel{
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        Image img;
        Timer timer;
        int count=0;
        public rectangle() {

            setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));
            setPreferredSize(new Dimension(100,100));
            timer=new Timer(800, new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent arg0) {
                    loadPic(count%5);
                    count++;
                    revalidate();
                    repaint();
                }
            });

            addMouseListener(new MouseAdapter() {

                @Override
                public void mouseEntered(MouseEvent arg0) {
                    count=0;
                    timer.start();
                }

                @Override
                public void mouseExited(MouseEvent arg0) {
                    timer.stop();
                }
            });
        }
        @Override
        protected void paintComponent(Graphics g){
            super.paintComponent(g);
            g.drawImage(img, 0, 0, 120, 100,this);
        }

        public void loadPic(int number){

            String address="";

            switch(number){
            case 0: address="img1.jpg";
            break;
            case 1: address="img2.jpg";
            break;
            case 2: address="img3.jpg";
            break;
            case 3: address="img4.jpg";
            break;
            default: address="img5.jpg";
            break;
            }

            try  
            {  
                img = ImageIO.read(getClass().getResourceAsStream(address));

            }  
            catch(Exception e){
                System.out.println("error in loading image");
            }

        }
    }

}

OTHER TIPS

Start with How to Write a Mouse-Motion Listener. You will need to determine when the mouse enters your prescribed area, you can use a java.awt.Rectangle to help with this as it has a contains(Point) method.

Then, take a look at How to Use Swing Timers, which you can use to trigger the changes in the picture.

Basically, as the mouse moves into your Rectangle, you would start the Swing Timer, which would trigger an action event, where by you would update which picture was to be displayed and call repaint. When the mouse moves out side of the Rectangle you would simply stop the timer.

Use ImageIcon array add set all path in ImageIcon when mouse enter on label, the image changes after 1 second.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class myImage extends JFrame implements  MouseMotionListener
{
    ImageIcon[] m=new ImageIcon[2]; 
    JLabel l;
    int i,l1;
    public myImage()
    {
        setLayout(null);
        setSize(1000,1000);
        setVisible(true);
        m[0]=new ImageIcon("m.jpg");
        m[1]=new ImageIcon("m1.jpg");
        l=new JLabel();
        l.setBounds(400,0,getWidth(),getHeight());
        add(l);
        l.addMouseMotionListener(this);
    }

    public void mouseMoved(MouseEvent e) 
    {
        if(i<2)
        {
            l.setIcon(m[i]);
            i++;
            try{
                Thread.sleep(1000);
            }
            catch(Exception e1)
            {
            }
        }
        else
        {
            i=0;
        }
    }

    public void mouseDragged(MouseEvent e) 
    {
        System.out.print("Mouse bye");
    }

    public static void main(String args[])
    {
        myImage i1=new myImage();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top