Show full Image when hover over thumbnail as Popup/Overlay

倖福魔咒の 提交于 2019-12-20 07:32:04

问题


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:


One way is to use a tool-tip.

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. ;)


来源:https://stackoverflow.com/questions/8965275/show-full-image-when-hover-over-thumbnail-as-popup-overlay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!