添加 JMenuItems 的有效方法

发布于 2024-10-15 12:34:57 字数 3921 浏览 1 评论 0原文

好吧,在我的 INV 程序是删除菜单项之前,但后来我就想……这太多了。那么,如果我为特定的右键单击项目添加菜单项而不是每次都删除呢?

因此,如果右键单击第 1 项,菜单中将添加“使用”和“放置”。然后,一旦您选择了选项,JMenu 就会删除所有内容,因此它就在我们开始的地方。然后,如果您右键单击 ITem 2,它会添加“使用”和“取消”。看看我要去哪里?

我尝试自己做,但我就是不知道该怎么做——例如,要添加一个新的 JMenuItem,您需要这样做:

popup.add(item = new JMenuItem("Cancel"));
item.addActionListener(menuListener);

并且,如您所见,添加一个动作侦听器。我无法在 if (actItemx == "Item 1") { 下执行此操作,所以...我该怎么办?

无论如何,这就是我到目前为止所拥有的:

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;

public class inv extends JApplet implements MouseListener
{
    public JList listbox;
    public JPopupMenu popup;
    public JMenuItem item;

    public void init()
    {
        ActionListener menuListener = new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                String invAction = event.getActionCommand();


                int itemSelect = listbox.getSelectedIndex();
                Object actItem = listbox.getModel().getElementAt(itemSelect);

                System.out.println("Popup menu item [" + invAction + "] [ " + actItem + " ] was pressed.");
            }
        };

        popup = new JPopupMenu();

        popup.add(item = new JMenuItem("Use"));
        item.addActionListener(menuListener);

        popup.add(item = new JMenuItem("Drop"));
        item.addActionListener(menuListener);

        popup.add(item = new JMenuItem("Cancel"));
        item.addActionListener(menuListener);



        String listData[] =
        {
            "Item 1","Item 2","Item 3","Item 4"
        };

        listbox = new JList( listData );
        listbox.addMouseListener( new MouseAdapter()
        {
            public void mousePressed(MouseEvent e)
            {
                if ( SwingUtilities.isRightMouseButton(e) )
                {
                    System.out.println("Row: " + getRow(e.getPoint()));
                    listbox.setSelectedIndex(getRow(e.getPoint()));
                }
            }
        }
        );

        listbox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        add(listbox);
        listbox.setVisible(true);
        listbox.setFocusable(false);


        listbox.addMouseListener(new MousePopupListener());
    }

    class MousePopupListener extends MouseAdapter
    {
        public void mousePressed(MouseEvent e)
        {
            checkPopup(e);
        }

        public void mouseClicked(MouseEvent e)
        {
            checkPopup(e);
        }

        public void mouseReleased(MouseEvent e)
        {
            checkPopup(e);
        }

        private void checkPopup(MouseEvent e)
        {
            if (e.isPopupTrigger())
            {

                int itemSelectx = listbox.getSelectedIndex();
                Object actItemx = listbox.getModel().getElementAt(itemSelectx);
                System.out.println("You pressed on " + actItemx);

            if (actItemx == "Item 1") {
                System.out.println("Removed cancel for " + actItemx);
                popup.remove(itemSelectx); // So upon right-click on Item 1, you won't see "Cancel" menu.
            }

                popup.show(inv.this, e.getX(), e.getY());
                popup.revalidate();
            }
        }
    }

    private int getRow(Point point)
    {
        return listbox.locationToIndex(point);
    }

    public void mouseEntered(MouseEvent e)
    {
    }

    public void mouseReleased(MouseEvent e)
    {
    }

    public void mousePressed(MouseEvent e)
    {
    }

    public void mouseClicked(MouseEvent e)
    {
    }

    public void mouseExited(MouseEvent e)
    {
    }
}

OK so before my INV program was to REMOVE menu items but then I was all like.. that's too much. So what if I were to ADD menu items for specific Right-clicked items INSTEAD of removing every time?

So, if you right-clicked on Item 1, you'd get "Use" and "Drop" added to the menu. Then ONCE you choose your option, the JMenu would delete everything so it would be right where we started. Then if you right-clicked on ITem 2, it would add "Use" and "Cancel". See where I'm going?

I tried doing it myself, but I just can't figure out how to do it -- for example, to add a new JMenuItem, you need to do this:

popup.add(item = new JMenuItem("Cancel"));
item.addActionListener(menuListener);

and, as you can see, add an actionlistener. I can't do that under if (actItemx == "Item 1") { so... what do I do?

Anyways, here's what I have so far:

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;

public class inv extends JApplet implements MouseListener
{
    public JList listbox;
    public JPopupMenu popup;
    public JMenuItem item;

    public void init()
    {
        ActionListener menuListener = new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                String invAction = event.getActionCommand();


                int itemSelect = listbox.getSelectedIndex();
                Object actItem = listbox.getModel().getElementAt(itemSelect);

                System.out.println("Popup menu item [" + invAction + "] [ " + actItem + " ] was pressed.");
            }
        };

        popup = new JPopupMenu();

        popup.add(item = new JMenuItem("Use"));
        item.addActionListener(menuListener);

        popup.add(item = new JMenuItem("Drop"));
        item.addActionListener(menuListener);

        popup.add(item = new JMenuItem("Cancel"));
        item.addActionListener(menuListener);



        String listData[] =
        {
            "Item 1","Item 2","Item 3","Item 4"
        };

        listbox = new JList( listData );
        listbox.addMouseListener( new MouseAdapter()
        {
            public void mousePressed(MouseEvent e)
            {
                if ( SwingUtilities.isRightMouseButton(e) )
                {
                    System.out.println("Row: " + getRow(e.getPoint()));
                    listbox.setSelectedIndex(getRow(e.getPoint()));
                }
            }
        }
        );

        listbox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        add(listbox);
        listbox.setVisible(true);
        listbox.setFocusable(false);


        listbox.addMouseListener(new MousePopupListener());
    }

    class MousePopupListener extends MouseAdapter
    {
        public void mousePressed(MouseEvent e)
        {
            checkPopup(e);
        }

        public void mouseClicked(MouseEvent e)
        {
            checkPopup(e);
        }

        public void mouseReleased(MouseEvent e)
        {
            checkPopup(e);
        }

        private void checkPopup(MouseEvent e)
        {
            if (e.isPopupTrigger())
            {

                int itemSelectx = listbox.getSelectedIndex();
                Object actItemx = listbox.getModel().getElementAt(itemSelectx);
                System.out.println("You pressed on " + actItemx);

            if (actItemx == "Item 1") {
                System.out.println("Removed cancel for " + actItemx);
                popup.remove(itemSelectx); // So upon right-click on Item 1, you won't see "Cancel" menu.
            }

                popup.show(inv.this, e.getX(), e.getY());
                popup.revalidate();
            }
        }
    }

    private int getRow(Point point)
    {
        return listbox.locationToIndex(point);
    }

    public void mouseEntered(MouseEvent e)
    {
    }

    public void mouseReleased(MouseEvent e)
    {
    }

    public void mousePressed(MouseEvent e)
    {
    }

    public void mouseClicked(MouseEvent e)
    {
    }

    public void mouseExited(MouseEvent e)
    {
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心在旅行 2024-10-22 12:34:57

为每种类型的项目设置不同的 JPopup 菜单怎么样?我的意思是你有看起来像这样的东西:

public JPopupMenu useDropPopup;
public JPopupMenu useCancelPopup;

public void init() {
   ActionListener menuListener = new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                String invAction = event.getActionCommand();


                int itemSelect = listbox.getSelectedIndex();
                Object actItem = listbox.getModel().getElementAt(itemSelect);

                System.out.println("Popup menu item [" + invAction + "] [ " + actItem + " ] was pressed.");
            }
        };

   useDropPopup = new JPopupMenu();
   useCancelPopup = new JPopupMenu();

   JMenuItem useMenuItem = new JMenuItem("Use");
   useMenuItem.addActionListener(menuListener);
   JMenuItem dropMenuItem = new JMenuItem("Drop");
   dropMenuItem.addActionListener(menuListener);
   JMenuItem cancelMenuItem = new JMenuItem("Cancel");
   cancelMenuItem.addActionListener(menuListener);

   useDropPopup.add(useMenuItem);
   useDropPopup.add(dropMenuItem);

   useCancelPopup.add(useMenuItem);
   useCancelPopup.add(cancelMenuItem);

   // ... etc bring up the appropriate popup depending on the item.
}

另外,你不应该将 JMenuItem 分配给方法调用内部的项目。这是不好的做法。还可以考虑为每个菜单项使用不同的动作侦听器,以便您可以分离每个菜单项的功能代码,例如:

useMenuItem.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent event) {
      useMenuAction(event);
   }
};

// ... after the init method

public void useMenuAction(ActionEvent evt) {
   // Add specific use menu code here.
}

What about setting up different JPopup menu's for each type of item. What I mean by that is you have something that looks like this:

public JPopupMenu useDropPopup;
public JPopupMenu useCancelPopup;

public void init() {
   ActionListener menuListener = new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                String invAction = event.getActionCommand();


                int itemSelect = listbox.getSelectedIndex();
                Object actItem = listbox.getModel().getElementAt(itemSelect);

                System.out.println("Popup menu item [" + invAction + "] [ " + actItem + " ] was pressed.");
            }
        };

   useDropPopup = new JPopupMenu();
   useCancelPopup = new JPopupMenu();

   JMenuItem useMenuItem = new JMenuItem("Use");
   useMenuItem.addActionListener(menuListener);
   JMenuItem dropMenuItem = new JMenuItem("Drop");
   dropMenuItem.addActionListener(menuListener);
   JMenuItem cancelMenuItem = new JMenuItem("Cancel");
   cancelMenuItem.addActionListener(menuListener);

   useDropPopup.add(useMenuItem);
   useDropPopup.add(dropMenuItem);

   useCancelPopup.add(useMenuItem);
   useCancelPopup.add(cancelMenuItem);

   // ... etc bring up the appropriate popup depending on the item.
}

Also, you should not assign a JMenuItem to item inside of a method call. That's bad practice. Also consider using different actionlisteners for each menu item so you can separate the functional code of each menu item, ex:

useMenuItem.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent event) {
      useMenuAction(event);
   }
};

// ... after the init method

public void useMenuAction(ActionEvent evt) {
   // Add specific use menu code here.
}
慈悲佛祖 2024-10-22 12:34:57

这主要是对 jluzwick 答案的补充:

您可以使用 Action,而不是创建 JMenuItem 并向其添加 ActionListener - 这基本上是 ActionListener 与名称、可选的 Icon 和一些其他属性的组合。 (最简单的是从 AbstractAction 扩展,覆盖 actionPerformed-Method。)

然后将 Action 添加到 JMenu,它将构造 JMenuItem 本身。 (您还可以在其他地方使用相同的 Action 对象,例如按钮、“普通”菜单栏等)

This is mostly an addition to the answer from jluzwick:

Instead of creating a JMenuItem and adding an ActionListener to it, you can use a Action - this is basically a combination of a ActionListener with a name, optionally Icon and some other properties. (Most simply extend from AbstractAction, overriding the actionPerformed-Method.)

Then add the Action to your JMenu, and it will construct the JMenuItem itself. (You can also use the same Action object on other places, like Buttons, the "normal" menu bar, etc.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文