Swing图层的应用——实现tooltip显示

时间:2021-06-26 15:26:46

没有错是世纪前的swing。

在使用Swing的时候有个问题一直没有解决,就是Swing自带的tooltip不会跟随鼠标进行移动,而且移动到边界就会遮挡的问题。JCompoent有个createTooltip()方法,但这个方法只能改变tooltip的外观,不能改变行为。事实上tooltip的行为和设置全都是由TooltipManager来进行,所以解决的方法只有自己撸一个类似于ToolTipManager了。

实现方法

从原来TooltipManager的实现原理来看(见Tooltipmanager源码),它是通过三个控制出现、持续和隐藏的线程,和JPopupFactory来实现的。

ToolTipManager() {
enterTimer = new Timer(750, new insideTimerAction());
enterTimer.setRepeats(false);
exitTimer = new Timer(500, new outsideTimerAction());
exitTimer.setRepeats(false);
insideTimer = new Timer(4000, new stillInsideTimerAction());
insideTimer.setRepeats(false); // create accessibility actions
postTip = KeyStroke.getKeyStroke(KeyEvent.VK_F1,Event.CTRL_MASK);
postTipAction = new Actions(Actions.SHOW);
hideTip = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
hideTipAction = new Actions(Actions.HIDE); moveBeforeEnterListener = new MoveBeforeEnterListener();
}

但我向做一个轻量级别的,即只用一个控制出现的线程,弹出层我不使用JPopupFactory,用的是JComponent,使用JlayeredPane来控制图层层叠次序。

实现之前

实现之前建议先了解JRootPane、JLayeredPane的相关知识。以及Java API文档对这两个的解释。

Oracle官方有文档:How to Use Root Panes、How to Use Layered Panes

概括来说,就是:一个Window(JDialog、JFrame等),窗口显示区域是JRootPane区域,如图,menu区域(可无)+ContentPane区域=JRootPane区域。

如果一个窗口没有设置menu,那么ContentPane区域=JRootPane区域。

Swing图层的应用——实现tooltip显示

如图,JRootPane里面有两个儿子:GlassPane,JLayeredPane两个图层。GlassPane的图层次序是0,代表顶层,JLayeredPane的次序是-1,代表底层。GlassPane默认是不显示的。JLayeredPane也有两个儿子:conentPane和JMenubar,其中contentPane是我们常用的图层。而我们要做的就是再给JlayeredPane加一个儿子,把ToolTip加进去,当然你也可以加在GlassPane里面。

Swing图层的应用——实现tooltip显示

Swing图层的应用——实现tooltip显示

(-1:底层 0:顶层)

JRootPane.java

public void setLayeredPane(JLayeredPane layered) {
...... this.add(layeredPane, -1);
} public void setGlassPane(Component glass) {
......
this.add(glassPane, 0);
......
}

JRootPane 的Layeredpane 和 GlassPane的初始化方法。

实现组件

1、对于默认JToolTip来说其实它就是一个JLabel,对于多行文本的显示比较差,往往需要使用HTML标记来使用。

所以我自己实现的组件使用了JTextPane,支持html、以及多行文本形式。

2、ToolTip需要给鼠标划过的组件添加侦听,当鼠标移除后要及时移除侦听,我还采用了一个变量记录上一个侦听,防止侦听溢出。

3、动态计算ToolTip位置,当移动到右、下边界时会分别平移到鼠标左、上,防止遮挡。

4、使用一个线程计时,实现弹出时间,和tooltipmanager不同的是,鼠标不移开组件,Tooltip就不会消失。

代码实现

PopTimingTip.java

 package;

 import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent; import javax.swing.JComponent;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.border.LineBorder; public class PopTimingTip extends JComponent { private JPanel mainPanel;
private JTextPane textComponent;
private TipListener tipListener;
private Component tipParent;
private int initTime = 0;
private int lastTime = 0;
private int vanishTime = 0;
private JLayeredPane windowLayer;//窗口的遮罩层,不能随便修改,只作父对象应用
private Point constPoint = new Point(12, 5);//距离鼠标常量,防止鼠标遮挡
private Point constPoint2 = new Point(2,2);//常量2 防止离鼠标太近,触发mouseexit事件
private Timer tipTimer;
private TipTimerListener tipTimerListener;
private static PopTimingTip popTimingTip;
private JRootPane rootPane;//当前根面板
private Dimension curTipSize;
private int curConType; /**
* 单例外部不允许初始化
*/
private PopTimingTip() {
super();
initTip();
} public static PopTimingTip getInstance() {
if(popTimingTip == null) {
popTimingTip = new PopTimingTip();
}
return popTimingTip;
} private void initTip() {
this.setLayout(new BorderLayout());
this.setOpaque(false);
//this.setBorder(null);
this.setVisible(false);
textComponent = new JTextPane();
textComponent.setContentType("text/html");
textComponent.setBorder(new LineBorder(Color.BLACK));
textComponent.setBackground(new Color(245, 245, 245));
mainPanel = new JPanel(new BorderLayout());
mainPanel.add(textComponent, BorderLayout.CENTER);
this.add(mainPanel, BorderLayout.CENTER); tipTimerListener = new TipTimerListener();
tipTimerListener.state = 0; tipListener = new TipListener();
tipTimer = new Timer(0, tipTimerListener);
tipTimer.setRepeats(false); curTipSize = new Dimension(0,0);
}
public void showTip() {
this.setVisible(true);
}
/**
* 为某个组件设置tip
* @param parent 显示tooltip的对象
* @param text
*/
public void showTipText(JComponent parent, String text) {
if(parent == null) {
return;
}
//如果进入了新的组件,先从旧组件中移除侦听防止泄漏
if(tipParent != null && tipParent != parent) {
tipParent.removeMouseListener(tipListener);
tipParent.removeMouseMotionListener(tipListener);
}
tipParent = parent; rootPane = parent.getRootPane();
//防止异常获取不了根面板的情况
if(rootPane == null) {
return;
} JLayeredPane layerPane = rootPane.getLayeredPane();
//先从旧面板中移除tip
if(windowLayer != null && windowLayer != layerPane) {
windowLayer.remove(this);
}
windowLayer = layerPane;
//防止还有没有移除侦听的组件
tipParent.removeMouseListener(tipListener);
tipParent.removeMouseMotionListener(tipListener);
layerPane.remove(this);
//放置tip在遮罩窗口顶层
layerPane.add(this, JLayeredPane.POPUP_LAYER);
//窗口遮罩层添加侦听
tipParent.addMouseMotionListener(tipListener);
tipParent.addMouseListener(tipListener);
//测试侦听器数量
//System.out.println(tipParent.getMouseListeners().length + " " + tipParent.getMouseMotionListeners().length);
//设置tiptext
textComponent.setText(text);
mainPanel.doLayout();
//this.setPreferredSize(textComponent.getPreferredSize());
curTipSize = textComponent.getPreferredSize();
this.setSize(textComponent.getPreferredSize().width, textComponent.getPreferredSize().height);
} /**
* 初始化toolTip
* @param contentType 0:html 1:文本类型
* @param initTime 鼠标进入后等待时间
* @param lastTime 持续时间(未完成)
* @param vanishTime 鼠标移走后消失时间(未完成)
*/
public void setConfigure(int contentType, int initTime) {
if(contentType == 0 && curConType != contentType) {
textComponent.setContentType("text/html");
} else if(contentType ==1 && curConType != contentType) {
textComponent.setContentType("text/plain");
}
curConType = contentType;
this.initTime = initTime;
//this.vanishTime = vanishTime;
//this.lastTime = lastTime;
}
/**
* 坐标转换,标签跟随鼠标移动
*/
private void followWithMouse(MouseEvent e) {
if(windowLayer == null) {
return;
} Point screenPoint = e.getLocationOnScreen(); SwingUtilities.convertPointFromScreen(screenPoint, windowLayer); int newLocationX = screenPoint.x + constPoint.x;
int newLocationY = screenPoint.y + constPoint.y; Dimension tipSize = textComponent.getPreferredSize();
if(newLocationX + tipSize.width > rootPane.getWidth()) {
newLocationX = screenPoint.x - tipSize.width - constPoint2.x;
}
if(newLocationY + tipSize.height > rootPane.getHeight()) {
newLocationY = screenPoint.y - tipSize.height - constPoint2.y;
}
this.setLocation(newLocationX, newLocationY);
//textComponent.getPreferredSize()在html初始化计算的时候有问题,重算一次
if(!curTipSize.equals(textComponent.getPreferredSize())) {
this.setSize(textComponent.getPreferredSize().width, textComponent.getPreferredSize().height);
}
} private void setTipState(int state) {
tipTimer.stop();//停止上一次的任务
if(state == 0) {//进入组件,延迟显示
tipTimerListener.state = 0;
tipTimer.setInitialDelay(initTime);
tipTimer.start();
} else if(state == 1) {//鼠标移出,组件消失
tipTimerListener.state = 1;
PopTimingTip.this.setVisible(false);
}
} private class TipTimerListener implements ActionListener {
int state;
public void actionPerformed(ActionEvent e) {
if(state == 0) {
PopTimingTip.this.setVisible(true);
}
}
} /**
* 鼠标移除后及时清除侦听防止侦听器溢出
*/
private void removeTipAndListener() {
if(tipParent == null) {
return;
}
tipParent.removeMouseListener(tipListener);
tipParent.removeMouseMotionListener(tipListener);
if(windowLayer != null) {
windowLayer.remove(this);
}
} private class TipListener extends MouseAdapter {
public void mouseEntered(MouseEvent e) {
setTipState(0);
followWithMouse(e);
} /**
* 鼠标移出对象时,移除对象的侦听和ToolTip
*/
public void mouseExited(MouseEvent e) {
setTipState(1);
followWithMouse(e);
removeTipAndListener();
} //在组件上移动时触发
public void mouseMoved(MouseEvent e){
setTipState(0);
followWithMouse(e);
} public void mouseClicked(MouseEvent e) {
if((e.getModifiers() & MouseEvent.BUTTON3_MASK) != 0) {//右键点击,tip消失
setTipState(1);
followWithMouse(e);
removeTipAndListener();
}
}
} }

ToolTipTest.java

package swingpac;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent; import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder; public class ToolTipTest extends JFrame { private JPanel contentPane; /**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ToolTipTest frame = new ToolTipTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} /**
* Create the frame.
*/
public ToolTipTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
contentPane.setLayout(new FlowLayout());
initTip();
} private void initTip() {
JButton btn = null;
MListener m = new MListener();
for(int i=0; i<10; i++) {
btn = new JButton();
btn.setName("第"+i+"个按钮!");
btn.setText("按钮"+i);
btn.addMouseListener(m);
contentPane.add(btn);
}
} class MListener extends MouseAdapter {
public void mouseEntered(MouseEvent e) {
JButton btn = (JButton)e.getSource();
StringBuilder sb = new StringBuilder();
sb.append("当前进入的按钮是:\n")
.append(btn.getName()).append("\n")
.append("正在进行演示自定义Tooltip!\n")
.append("请自行查看源码"); PopTimingTip.getInstance().setConfigure(1, 300);
PopTimingTip.getInstance().showTipText(btn, sb.toString());
}
} }

效果演示(红色为鼠标位置)

Swing图层的应用——实现tooltip显示

遇到边界平移

Swing图层的应用——实现tooltip显示

总结

利用JLayeredPane还可以做出其它组件,比如弹出层录入等,个人感觉比Popup要轻量级,而且不会使界面失去焦点,阻塞用户操作。