秋千上在mousePressed事件上时如何在鼠标旁边显示消息? [英] How to display a message next to the mouse when on mousePressed event in swing?

查看:106
本文介绍了秋千上在mousePressed事件上时如何在鼠标旁边显示消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当在GUI中单击鼠标时,我都试图在鼠标旁边显示一个文本框.当您将鼠标悬停在Internet上的链接上时,同样的想法会将预览显示为一个小的弹出气泡.我想在单击时使用它.

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.

推荐答案

以下是您的示例:

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

}

这篇关于秋千上在mousePressed事件上时如何在鼠标旁边显示消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆