1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| public class DemoTooltip {
private static final String IMAGE_PATH = "suricate.png";
private static final String TOOLTIP_TEXT = "tooltip";
public static void main(String[] args) {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel((LayoutManager) null, true);
panel.setBackground(Color.WHITE);
frame.getContentPane().add(panel);
JLabel label = create();
JToolTip toolTip = label.createToolTip();
toolTip.setTipText(label.getToolTipText());
panel.add(label);
KeyboardFocusManager manager = KeyboardFocusManager
.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher(new KeyEventDispatcher() {
private Timer timer;
private Popup popup;
public boolean dispatchKeyEvent(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
move(0, -1);
break;
case KeyEvent.VK_DOWN:
move(0, 1);
break;
case KeyEvent.VK_RIGHT:
move(1, 0);
break;
case KeyEvent.VK_LEFT:
move(-1, 0);
break;
}
return false;
}
private void move(int dx, int dy) {
ToolTipManager.sharedInstance().unregisterComponent(label);
Point location = label.getLocation();
location.x += dx;
location.y += dy;
int x = label.getLocationOnScreen().x + label.getWidth();
int y = label.getLocationOnScreen().y + label.getHeight()+label.getHeight()/2;
Rectangle screenBounds = label.getGraphicsConfiguration().getBounds();
if ( x+toolTip.getWidth()>screenBounds.getMaxX() ) {
x=(int)screenBounds.getMaxX()-toolTip.getWidth();
}
if ( x<screenBounds.getMinX() ) {
x=(int)screenBounds.getMinX();
}
if ( y+toolTip.getHeight()>screenBounds.getMaxY() ) {
y=(int)screenBounds.getMaxY()-toolTip.getHeight();
}
if ( y<screenBounds.getMinY() ) {
y=(int)screenBounds.getMinY();
}
if ( popup!=null ) {
popup.hide();
}
label.setLocation(location);
popup = PopupFactory.getSharedInstance().getPopup(label,
toolTip, x,
y);
popup.show();
if ( timer!=null ) {
timer.stop();
}
timer = new Timer(ToolTipManager.sharedInstance().getDismissDelay(),
(e) -> {
popup.hide();
popup=null;
ToolTipManager.sharedInstance().registerComponent(label);
});
timer.start();
}
});
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static JLabel create() {
JLabel label = new JLabel();
ImageIcon icon = new ImageIcon(IMAGE_PATH);
if ( icon.getIconWidth()==0 || icon.getIconHeight()==0 ) throw new IllegalStateException("Image not found or zero size");
label.setIcon(icon);
label.setToolTipText(TOOLTIP_TEXT);
label.setSize(icon.getIconWidth(), icon.getIconHeight());
return label;
}
} |
Partager