MouseListener给show()方法带来问题 [英] MouseListener is giving problems with show() method

查看:115
本文介绍了MouseListener给show()方法带来问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户右键单击我的应用程序中的表行时,我想显示一个小的上下文菜单.我的计划是为此使用定制的MouseListener来调用show()方法.这是我的代码:

I want to display a small context menu when a user right clicks a table row in my application. My plan was to use a custom made MouseListener for this that calls the show() method. Here is my code:

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.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.SwingUtilities;

class TableMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
    JTable table = (JTable)(e.getSource());
    Point p = e.getPoint();
    int row = table.rowAtPoint(p);
    int col = table.columnAtPoint(p);

// The autoscroller can generate drag events outside the Tables range.
if ((col == -1) || (row == -1)) {
        return;
}

    if (SwingUtilities.isRightMouseButton(e)) {
        JPopupMenu pop = new JPopupMenu("Row "+row);
        JMenuItem menu1 = new JMenuItem("Wijzigen");
        menu1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                //do things, still have to make that
            }
        });
        pop.show(menu1, p.x, p.y);

    }
}
}

现在我的问题是:当我运行我的应用程序时,我右键单击一个表行,它将弹出此错误:

Now my problem is: when i run my application, and I right click a table row, it pops out this error:

Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
at java.awt.Component.getLocationOnScreen_NoTreeLock(Unknown Source)
at java.awt.Component.getLocationOnScreen(Unknown Source)
at javax.swing.JPopupMenu.show(Unknown Source)
at TableMouseListener.mousePressed(TableMouseListener.java:34)

这到底是怎么了?

推荐答案

  • JMenuItem未添加到JPopup中,则JMenuItem不应为isDisplayable

    • JMenuItem isn't added to the JPopup, then JMenuItem shoudn't be isDisplayable

      准备此容器,不要即时创建

      prepare this container, dont't to create on fly ,

      将整个弹出式容器创建为局部变量或类的返回值,void,无论如何

      create whole popup container as local variable or as returns from class, void, whatever

      a)也准备与JMenuItems

      b)覆盖maybeShowPopup,那么您可以在此进行任何操作(必须在EDT上完成)

      b) override maybeShowPopup, then there you can manage whatever (must be done on EDT)

      其余重要方法

      这篇关于MouseListener给show()方法带来问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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