How to display a message next to the mouse when on mousePressed event in swing?

安稳与你 提交于 2020-01-26 04:57:11

问题


I am trying to display a text box next to the mouse whenever it is clicked in a GUI. The same idea when you hover your mouse over a link on the internet, it shows a preview as a small popup bubble. I would like to have it when clicked.


回答1:


Here is an example for you:

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

}


来源:https://stackoverflow.com/questions/47139194/how-to-display-a-message-next-to-the-mouse-when-on-mousepressed-event-in-swing

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