Swing鼠标悬停时巧用上下文菜单显示提示信息

来源:互联网 发布:广西电子政务云计算 编辑:程序博客网 时间:2024/06/06 10:44

     Swing的大多数控件都已经实现了setToolTip接口,当鼠标悬停时会显示设置好的提示信息。但是当需要精确地显示复杂的提示信息时就力不从心。本文就介绍利用上下文菜单来显示复杂的提示信息。

     首先需要解决在鼠标悬停时在何地显示提示信息的问题,这可以通过为控件添加MouseMotionListener来实现。通过MouseEvent的Point可以知道当前鼠标悬停的精确地点,再判断相对于控件的位置,从而得出是否需要显示提示信息。

     其次当需要显示提示信息时,需要运用上下文菜单在相对控件的特定位置显示提示信息。 上下文菜单也是一个面板,可以设置布局管理器和添加控件,把所有的提示信息封装到一个JPanel里面,然后把该panel添加到菜单里面即可(BorderLayout居中)。具体代码如下。

table.addMouseMotionListener(new MouseMotionListener() {@Overridepublic void mouseMoved(MouseEvent e) {Point point = e.getPoint();int rowIndex = table.rowAtPoint(point);if (rowIndex > 0) {JPopupMenu popup = new JPopupMenu();popup.setLayout(new BorderLayout());JPanel infoPanel = createtInfoPanel();popup.add(infoPanel, BorderLayout.CENTER);popup.show(table, (int)point.getX(), (int)point.getY());}}@Overridepublic void mouseDragged(MouseEvent e) {}});

private JPanel createtInfoPanel() {JPanel infoPanel = new JPanel();MigLayout layout = new MigLayout("", "[grow,fill]", "20[pref!]20");infoPanel.setLayout(layout);infoPanel.add(new JLabel("Cool Thing"));return infoPanel;}


     通过以上方式,可以精确控制只有在特定的某一个位置才显示提示信息,比如某一列,或者某一特殊的单元格。也可以把复杂的提示信息放到面板中进行布局,style和显示。功能强大。

原创粉丝点击