好,所以,这次我要尝试一下。我使用了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)
ang
这是代码:
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)
{
}
}
最佳答案
在创建对象之前,popup为null。
在向其中添加项目之前,请创建JPopupMenu成员弹出窗口。