Show full Image when hover over thumbnail as Popup

2020-05-05 17:50发布

I display thumbnails in a JPanel. When hovering over such a thumbnail, I want to display its full version in an overlay over the thumbnail.

Using HTML I would just create a div with the proper positions and a high z-index, so that it overlays everything else. Is something similiar and lightweight possible with Swing?

1条回答
▲ chillily
2楼-- · 2020-05-05 18:36

One way is to use a tool-tip.

ThumbTip

import javax.swing.*;
import java.awt.GridLayout;

class ThumbTip {

    private static final String HTML = "<html><body>";

    ThumbTip(String[] album) {
        JPanel p = new JPanel(new GridLayout(1,0,2,2));
        for (String url : album) {
            String s = HTML + "<img src='" + url.toString() + "'";
            String size = " width=200 height=150";
            JLabel l = new JLabel(s + size + ">");
            l.setToolTipText(s + ">");
            p.add(l);
        }
        JOptionPane.showMessageDialog(null, p);
    }

    public static void main(String[] args) {
        final String[] urls = {
            "http://pscode.org/media/stromlo1.jpg",
            "http://pscode.org/media/stromlo2.jpg"
        };
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ThumbTip(urls);
            }
        });
    }
}

Note:

  1. In this demo. the tool-tip image is downloaded from the net each time it is used. Be patient.
  2. I did not bother to 'thumbnail' the original images. 'Batteries not included'. The latest edit of the source use HTML (the width/height specified for the image) to shrink the 'thumbnails'. I won't update the screenshot.
  3. Ultimately the suggestion of using a JWindow is better, since it gives you more control of where and for how long the pop-up appears, as well as its exact look. But this hack is significantly shorter. ;)
查看更多
登录 后发表回答