如何在swing中的mousePressed事件上显示鼠标旁边的消息?

时间:2017-11-06 14:29:06

标签: java swing mouseevent

我试图在GUI中单击鼠标时显示鼠标旁边的文本框。将鼠标悬停在互联网上的链接上时,同样的想法是将预览显示为小弹出气泡。点击后我想拥有它。

1 个答案:

答案 0 :(得分:1)

以下是您的示例:

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;


public class CustomTip implements Runnable {

    private Popup popup;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new CustomTip());
    }

    @Override
    public void run() {
        JPanel panel = new JPanel();
        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (popup != null) {
                    popup.hide();
                }
                JLabel text = new JLabel("You've clicked at: " + e.getPoint());
                popup = PopupFactory.getSharedInstance().getPopup(e.getComponent(), text, e.getXOnScreen(), e.getYOnScreen());
                popup.show();
            }
        });
        JFrame frm = new JFrame("Test");
        frm.add(panel);
        frm.setSize(400, 300);
        frm.setLocationRelativeTo(null);
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setVisible(true);
    }

}