好的,所以,这次我试试这个。我使用了JMenuItem和JPopupMenu,我得到了这个NPE。
当我尝试运行它时,我收到此错误:
java.lang.NullPointerException
at inv.init(inv.java:28)
at sun.applet.AppletPanel.run(AppletPanel.java:424)
at java.lang.Thread.run(Thread.java:619)
荡。
这是代码:
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();
System.out.println("Popup menu item [" + invAction + "] was pressed.");
}
};
popup.add(item = new JMenuItem("Use"));
item.setHorizontalTextPosition(JMenuItem.RIGHT);
item.addActionListener(menuListener);
popup.add(item = new JMenuItem("Drop"));
item.setHorizontalTextPosition(JMenuItem.RIGHT);
item.addActionListener(menuListener);
popup.add(item = new JMenuItem("Cancel"));
item.setHorizontalTextPosition(JMenuItem.RIGHT);
item.addActionListener(menuListener);
addMouseListener(new MousePopupListener());
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);
}
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())
{
popup.show(inv.this, e.getX(), e.getY());
}
}
}
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)
{
}
}
答案 0 :(得分:4)
在创建对象之前,弹出窗口为空。
在向其添加项目之前创建JPopupMenu成员弹出窗口。
答案 1 :(得分:0)
popup
尚未初始化。
答案 2 :(得分:0)
JPopupMenu popup = new JPopupMenu();