帮忙看一下:JPopupMenu.add(action a)问题
编译时不出错,运行时如下错误:
D:\temp>java ToolDemo
Exception in thread "main" java.lang.NullPointerException
at javax.swing.JPopupMenu.createActionComponent(Unknown Source)
at javax.swing.JPopupMenu.add(Unknown Source)
at ToolDemo.createPopupMenu(ToolDemo.java:52)
at ToolDemo.<init>(ToolDemo.java:90)
at ToolDemo.main(ToolDemo.java:103)
附码:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class ToolDemo extends JFrame{
protected JPopupMenu popupMenu;
protected JToolBar toolbar;
Action openAction;
Action saveAction;
Action closeAction;
Action exitAction;
protected void createActionObjects(){
ImageIcon icon;
icon = new ImageIcon("open.gif");
openAction = new AbstractAction("Open",icon){
public void actionPerformed(ActionEvent e){
//JOptionPane.showMessageDialog(this,"Command: Open");
}
};
icon = new ImageIcon("save.gif");
openAction = new AbstractAction("Save",icon){
public void actionPerformed(ActionEvent e){
//JOptionPane.showMessageDialog(this,"Command: "+"Save");
}
};
icon = new ImageIcon("close.gif");
closeAction = new AbstractAction("Close",icon){
public void actionPerformed(ActionEvent e){
//JOptionPane.showMessageDialog(this,"Command: "+"Close");
}
};
icon = new ImageIcon("exit.gif");
exitAction = new AbstractAction("Exit",icon){
public void actionPerformed(ActionEvent e){
//JOptionPane.showMessageDialog(this,"Command: "+"Exit");
System.exit(0);
}
};
}
protected void createPopupMenu(){
popupMenu = new JPopupMenu();
popupMenu.add(openAction);
popupMenu.add(saveAction);
popupMenu.add(closeAction);
popupMenu.addSeparator();
popupMenu.add(exitAction);
}
class PopupHandler extends MouseAdapter{
public void mousePressed(MouseEvent e){
if (e.isPopupTrigger()) popupMenu.show(e.getComponent(),e.getX(),e.getY());
}
public void mouseReleased(MouseEvent e){
if (e.isPopupTrigger()) popupMenu.show(e.getComponent(),e.getX(),e.getY());
}
}
protected void createToolbar(){
toolbar = new JToolBar();
toolbar.add(openAction);
toolbar.add(saveAction);
toolbar.add(closeAction);
toolbar.addSeparator();
toolbar.add(exitAction);
}
public ToolDemo(){
try{
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {}
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
createActionObjects();
createPopupMenu();
createToolbar();
addMouseListener(new PopupHandler());
Container content = getContentPane();
content.setLayout(new BorderLayout());
content.add(toolbar,BorderLayout.NORTH);
toolbar.setFloatable(true);
content.add(new JLabel("Click inside the window"));
}
public static void main(String args[]){
ToolDemo app = new ToolDemo();
app.setTitle("ToolDemo");
app.setSize(320,240);
app.show();
}
}