Search code examples
javaimageswingpaintcomponentmouse-listeners

How do I create a JPanel with two images where only a part of the one below is shown on mouse over?


I am trying to create a button panel where the button that was clicked becomes 'differently colored'; i.e show the background image. p.s I only need this approach(with 2 images), and not anything else. Thanks !

Eg:

public class TestPane extends JPanel {      

        private BufferedImage   imgUnclicked;
        private BufferedImage   imgClicked;
        private Point           mousePoint;

        public TestPane() {
            try {
                imgUnclicked = ImageIO.read(new File("C:\\Users\\Me\\Desktop\\tmp\\Uncolored.png"));
                imgClicked = ImageIO.read(new File("C:\\Users\\Me\\Desktop\\tmp\\Colored.png"));
            } catch (IOException ex) {
                Logger.getLogger(Spotlight.class.getName()).log(Level.SEVERE, null, ex);
            }

            addMouseMotionListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    mousePoint = e.getPoint();
                    repaint();
                }
            });
        }
    }
    @Override
    protected void paintComponent(Graphics g) {
        //Draw imgClicked
        //Draw imgUnclicked with some rectangular area around mouse click subtracted
    }
}

Solution

  • No need to reinvent the wheel. Instead use a JToggleButton (appropriately configured). A button will react to both mouse and keyboard input.

    import java.awt.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    
    class ChangeImageOnClick {
    
        public static void main(String[] args) throws Exception {
            URL url1 = new URL("https://i.sstatic.net/gJmeJ.png");
            final Image img1 = ImageIO.read(url1);
            URL url2 = new URL("https://i.sstatic.net/wCF8S.png");
            final Image img2 = ImageIO.read(url2);
            Runnable r = new Runnable() {
    
                @Override
                public void run() {
                    JToggleButton btn = new JToggleButton("Click me!");
                    btn.setIcon(new ImageIcon(img1));
                    btn.setSelectedIcon(new ImageIcon(img2));
    
                    btn.setContentAreaFilled(false);
                    btn.setBorderPainted(false);
    
                    JOptionPane.showMessageDialog(null, btn);
                }
            };
            SwingUtilities.invokeLater(r);
        }
    }