Nullpointerexception on line 32 (java)
OK, so, this time i DID try on this. I used the JMenuItem and JPopupMenu and I'm getting this NPE.
When I try to run it, I get this error:
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)
Dang.
Here's code:
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 is null until you create the object.
Create the JPopupMenu member popup before adding items to it.
popup
has not been initialized.
JPopupMenu popup = new JPopupMenu();
精彩评论