问题
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:
- In this demo. the tool-tip image is downloaded from the net each time it is used. Be patient.
I did not bother to 'thumbnail' the original images. 'Batteries not included'.The latest edit of the source use HTML (thewidth
/height
specified for theimage
) to shrink the 'thumbnails'. I won't update the screenshot.- 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