JList 右键单击​​显示菜单(使用、删除、取消)

发布于 2024-10-15 18:23:00 字数 1507 浏览 8 评论 0原文

我一直在互联网上寻找这个答案。我有一个简单的 JList,其中包含项目。当我右键单击时,我希望弹出一个菜单,其中显示“使用、删除、取消”或类似性质的内容。然而,我很难过。

下面的代码将生成一个简单的 JList,其中包含一些项目。我尝试在代码中添加右键单击,但它不起作用。帮助?

这是我到目前为止所拥有的:

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



public class inv extends JApplet implements MouseListener {

    JList listbox;



     public void init()
     {


    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) )
            {
                listbox.setSelectedIndex(getRow(e.getPoint()));
            }
        }
     });

    listbox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);


        add(listbox);
                    listbox.setVisible(true);

            listbox.setFocusable(false);

     }



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

      public void mousePressed(MouseEvent e) {
      }

      public void mouseReleased(MouseEvent e) {
      }

      public void mouseEntered(MouseEvent e) {
      }

      public void mouseExited(MouseEvent e) {
      }

      public void mouseClicked(MouseEvent e) {
      }


     public void stop()
     {
     }

     public void paint(Graphics g)
     {
     }

}

I've been scouring the internet for this answer. I have a simple JList with items inside it. When I right-click, I want a menu to pop-up that says "Use, drop, cancel" or something of that nature. HOWEVER, I'm stumped.

The code below will produce a simple JList with a few items inside. I tried adding a right-click in the code but it doesn't work. Help?

Here is what I have so far:

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



public class inv extends JApplet implements MouseListener {

    JList listbox;



     public void init()
     {


    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) )
            {
                listbox.setSelectedIndex(getRow(e.getPoint()));
            }
        }
     });

    listbox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);


        add(listbox);
                    listbox.setVisible(true);

            listbox.setFocusable(false);

     }



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

      public void mousePressed(MouseEvent e) {
      }

      public void mouseReleased(MouseEvent e) {
      }

      public void mouseEntered(MouseEvent e) {
      }

      public void mouseExited(MouseEvent e) {
      }

      public void mouseClicked(MouseEvent e) {
      }


     public void stop()
     {
     }

     public void paint(Graphics g)
     {
     }

}

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

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

发布评论

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

评论(3

一世旳自豪 2024-10-22 18:23:00

典型的错误之一可能是调用 JPopupMenu.setVisible(true) 并期望发生某些事情。该组件需要不同的方法来启动它。按照以下方式重写鼠标侦听器:

    listbox.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                JPopupMenu menu = new JPopupMenu();
                JMenuItem item = new JMenuItem("Say hello");
                item.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        JOptionPane.showMessageDialog(inv.this, "Hello "
                                + listbox.getSelectedValue());
                    }
                });
                menu.add(item);
                menu.show(inv.this, 5, listbox.getCellBounds(
                        listbox.getSelectedIndex() + 1,
                        listbox.getSelectedIndex() + 1).y);
            }
        }
    });

为了简短起见,我仅添加一项,但肯定可以添加更多项。我使用的 show 方法还需要指定菜单应出现在组件上的位置。可以从列表本身获取位置,如本例所示。

One of the typical mistakes may be to call JPopupMenu.setVisible(true) and expect something to happen. This component needs a different method to bring it up. Rewrite your mouse listener along the lines:

    listbox.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                JPopupMenu menu = new JPopupMenu();
                JMenuItem item = new JMenuItem("Say hello");
                item.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        JOptionPane.showMessageDialog(inv.this, "Hello "
                                + listbox.getSelectedValue());
                    }
                });
                menu.add(item);
                menu.show(inv.this, 5, listbox.getCellBounds(
                        listbox.getSelectedIndex() + 1,
                        listbox.getSelectedIndex() + 1).y);
            }
        }
    });

To make example short, I add one item only but surely more can be added. The show method I use also requires to specify where on the component the menu should appear. The location can be obtained from the list itself as seen in this example.

淡墨 2024-10-22 18:23:00

我不知道你的意思。下面的代码似乎按照您指定的方式工作,但除了删除任何数量的冗余或有错误的语句之外,它几乎就是您发布的内容。

/*
<applet code='inv' width='200' height='200'>
</applet>
*/
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
import javax.swing.*;

public class inv extends JApplet { //implements MouseListener {

    JList listbox;

     public void init()
     {


    String  listData[] = { "Item 1","Item 2","Item 3","Item 4" };
listbox = new JList( listData );

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

    listbox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        add(listbox);
                    // unnecessary
                    //listbox.setVisible(true);

            listbox.setFocusable(false);
     }



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

/** Why implement MouseListener, while adding a MouseAdapter?
Do you have ANY idea what your doing?

      public void mousePressed(MouseEvent e) {
      }

      public void mouseReleased(MouseEvent e) {
      }

      public void mouseEntered(MouseEvent e) {
      }

      public void mouseExited(MouseEvent e) {
      }

      public void mouseClicked(MouseEvent e) {
      }
*/

    /** What is this nonsense supposed to achieve?
    Don't override empty methods with empty implementations!
     public void stop()
     {
     }
     */

    /** What is this nonsense supposed to achieve?
     public void paint(Graphics g)
     {
     }
     */
}

输出

java.awt.event.MouseEvent[MOUSE_PRESSED,(31,22),absolute(39,72),button=3,modifiers=Meta+Button3,extModifiers=Button3,clickCount=1] on javax.swing.JList[,0,0,200x200,alignmentX=0.0,alignmentY=0.0,border=,flags=50331944,maximumSize=,minimumSize=,preferredSize=,fixedCellHeight=-1,fixedCellWidth=-1,horizontalScrollIncrement=-1,selectionBackground=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],selectionForeground=sun.swing.PrintColorUIResource[r=51,g=51,b=51],visibleRowCount=8,layoutOrientation=0]
Row: 1
java.awt.event.MouseEvent[MOUSE_PRESSED,(29,39),absolute(37,89),button=3,modifiers=Meta+Button3,extModifiers=Button3,clickCount=1] on javax.swing.JList[,0,0,200x200,alignmentX=0.0,alignmentY=0.0,border=,flags=50331944,maximumSize=,minimumSize=,preferredSize=,fixedCellHeight=-1,fixedCellWidth=-1,horizontalScrollIncrement=-1,selectionBackground=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],selectionForeground=sun.swing.PrintColorUIResource[r=51,g=51,b=51],visibleRowCount=8,layoutOrientation=0]
Row: 2
java.awt.event.MouseEvent[MOUSE_PRESSED,(36,65),absolute(468,192),button=3,modifiers=Meta+Button3,extModifiers=Button3,clickCount=1] on javax.swing.JList[,0,0,200x200,alignmentX=0.0,alignmentY=0.0,border=,flags=50331944,maximumSize=,minimumSize=,preferredSize=,fixedCellHeight=-1,fixedCellWidth=-1,horizontalScrollIncrement=-1,selectionBackground=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],selectionForeground=sun.swing.PrintColorUIResource[r=51,g=51,b=51],visibleRowCount=8,layoutOrientation=0]
Row: 3
java.awt.event.MouseEvent[MOUSE_PRESSED,(45,11),absolute(477,138),button=3,modifiers=Meta+Button3,extModifiers=Button3,clickCount=1] on javax.swing.JList[,0,0,200x200,alignmentX=0.0,alignmentY=0.0,border=,flags=50331944,maximumSize=,minimumSize=,preferredSize=,fixedCellHeight=-1,fixedCellWidth=-1,horizontalScrollIncrement=-1,selectionBackground=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],selectionForeground=sun.swing.PrintColorUIResource[r=51,g=51,b=51],visibleRowCount=8,layoutOrientation=0]
Row: 0

Tool completed successfully

I do not know what you mean. Here is code that seems to work like you specify, but apart from taking out any number of redundant or buggy statements, it is pretty much what you posted.

/*
<applet code='inv' width='200' height='200'>
</applet>
*/
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
import javax.swing.*;

public class inv extends JApplet { //implements MouseListener {

    JList listbox;

     public void init()
     {


    String  listData[] = { "Item 1","Item 2","Item 3","Item 4" };
listbox = new JList( listData );

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

    listbox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        add(listbox);
                    // unnecessary
                    //listbox.setVisible(true);

            listbox.setFocusable(false);
     }



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

/** Why implement MouseListener, while adding a MouseAdapter?
Do you have ANY idea what your doing?

      public void mousePressed(MouseEvent e) {
      }

      public void mouseReleased(MouseEvent e) {
      }

      public void mouseEntered(MouseEvent e) {
      }

      public void mouseExited(MouseEvent e) {
      }

      public void mouseClicked(MouseEvent e) {
      }
*/

    /** What is this nonsense supposed to achieve?
    Don't override empty methods with empty implementations!
     public void stop()
     {
     }
     */

    /** What is this nonsense supposed to achieve?
     public void paint(Graphics g)
     {
     }
     */
}

Output

java.awt.event.MouseEvent[MOUSE_PRESSED,(31,22),absolute(39,72),button=3,modifiers=Meta+Button3,extModifiers=Button3,clickCount=1] on javax.swing.JList[,0,0,200x200,alignmentX=0.0,alignmentY=0.0,border=,flags=50331944,maximumSize=,minimumSize=,preferredSize=,fixedCellHeight=-1,fixedCellWidth=-1,horizontalScrollIncrement=-1,selectionBackground=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],selectionForeground=sun.swing.PrintColorUIResource[r=51,g=51,b=51],visibleRowCount=8,layoutOrientation=0]
Row: 1
java.awt.event.MouseEvent[MOUSE_PRESSED,(29,39),absolute(37,89),button=3,modifiers=Meta+Button3,extModifiers=Button3,clickCount=1] on javax.swing.JList[,0,0,200x200,alignmentX=0.0,alignmentY=0.0,border=,flags=50331944,maximumSize=,minimumSize=,preferredSize=,fixedCellHeight=-1,fixedCellWidth=-1,horizontalScrollIncrement=-1,selectionBackground=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],selectionForeground=sun.swing.PrintColorUIResource[r=51,g=51,b=51],visibleRowCount=8,layoutOrientation=0]
Row: 2
java.awt.event.MouseEvent[MOUSE_PRESSED,(36,65),absolute(468,192),button=3,modifiers=Meta+Button3,extModifiers=Button3,clickCount=1] on javax.swing.JList[,0,0,200x200,alignmentX=0.0,alignmentY=0.0,border=,flags=50331944,maximumSize=,minimumSize=,preferredSize=,fixedCellHeight=-1,fixedCellWidth=-1,horizontalScrollIncrement=-1,selectionBackground=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],selectionForeground=sun.swing.PrintColorUIResource[r=51,g=51,b=51],visibleRowCount=8,layoutOrientation=0]
Row: 3
java.awt.event.MouseEvent[MOUSE_PRESSED,(45,11),absolute(477,138),button=3,modifiers=Meta+Button3,extModifiers=Button3,clickCount=1] on javax.swing.JList[,0,0,200x200,alignmentX=0.0,alignmentY=0.0,border=,flags=50331944,maximumSize=,minimumSize=,preferredSize=,fixedCellHeight=-1,fixedCellWidth=-1,horizontalScrollIncrement=-1,selectionBackground=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],selectionForeground=sun.swing.PrintColorUIResource[r=51,g=51,b=51],visibleRowCount=8,layoutOrientation=0]
Row: 0

Tool completed successfully
攒一口袋星星 2024-10-22 18:23:00

根据前面的答案,下面的代码将立即选择该项目(右键单击),并在鼠标单击旁边显示弹出窗口。

listbox.addMouseListener( new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
        if ( SwingUtilities.isRightMouseButton(e) ) {      
           listbox.setSelectedIndex(listbox.locationToIndex(e.getPoint()));

            JPopupMenu menu = new JPopupMenu();
            JMenuItem itemRemove = new JMenuItem("Remove");
            itemRemove.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    // This could probably be improved, but assuming you
                    // also keep the values in an ArrayList, you can 
                    // remove the element with this:
                    //array_list.remove(listbox.getSelectedValue());
                    //listbox.setListData((String[]) array_list.toArray(new String[array_list.size()]));

                    System.out.println("Remove the element in position " + listbox.getSelectedValue());

                }
            });
            menu.add(itemRemove);
            menu.show(listbox, e.getPoint().x, e.getPoint().y);            
        }
    }
});

有一个注释部分显示了删除该项目的可能方法;它假定存在一个 ArrayList(称为 array_list),其中包含 JList 上元素的副本。它使用方法to_array来刷新JList。应该有一种更有效的方法,但是如果您的列表很短,那么它应该足够了。

Based in the previous to answers, the below code would immediately select the item (on right click), and display the pop up next to the mouse click.

listbox.addMouseListener( new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
        if ( SwingUtilities.isRightMouseButton(e) ) {      
           listbox.setSelectedIndex(listbox.locationToIndex(e.getPoint()));

            JPopupMenu menu = new JPopupMenu();
            JMenuItem itemRemove = new JMenuItem("Remove");
            itemRemove.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    // This could probably be improved, but assuming you
                    // also keep the values in an ArrayList, you can 
                    // remove the element with this:
                    //array_list.remove(listbox.getSelectedValue());
                    //listbox.setListData((String[]) array_list.toArray(new String[array_list.size()]));

                    System.out.println("Remove the element in position " + listbox.getSelectedValue());

                }
            });
            menu.add(itemRemove);
            menu.show(listbox, e.getPoint().x, e.getPoint().y);            
        }
    }
});

There is a commented section that shows a possible way of removing the item; it assumes the existence of an ArrayList (called array_list) that contains a copy of the elements on the JList. It used the method to_array in order to refresh the JList. There should be a more efficient way, but if your list is short, it should be sufficient.

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