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

时间:2011-01-31 17:46:18

标签: java swing popup jlist japplet

我一直在网上搜索这个答案。我有一个简单的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)
     {
     }

}

3 个答案:

答案 0 :(得分:5)

我不知道你的意思。以下代码似乎与您指定的一样,但除了删除任何数量的冗余或错误语句之外,它几乎就是您发布的内容。

/*
<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

答案 1 :(得分:4)

一个典型的错误可能是致电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方法还需要指定菜单应该出现在组件的哪个位置。可以从列表本身获取位置,如本例所示。

答案 2 :(得分:2)

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

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 like 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。应该有一种更有效的方法,但如果你的清单很短,那就足够了。