Menu GUI help in Java
I can't compile this code because of several errors. Most of the errors are under the initUI() method, which was copied from a tutorial site. How do I fix this?
ActionEvent cannot be resolved to a type MenuGUI.java /Misc/src line 35 Java Problem
ActionListener cannot be resolved to a type MenuGUI.java /Misc/src line 34 Java Problem
KeyEvent cannot be resolved to a variable MenuGUI.java /Misc/src line 29 Java Problem
KeyEvent cannot be resolved to a variable MenuGUI.java /Misc/src line 32 Java Problem
The method addActionListener(ActionListener) in the type AbstractButton is not applicable for the arguments (new ActionListener(){}) MenuGUI.java /Misc/src line 34 Java Problem
import javax.swing.*;
import java.awt.event.*;
public class MenuGUI extends JFrame{
private static final long serialVersionUID = 1L;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MenuGUI ex = new MenuGUI();
ex.setVisible(true);
}
});
}
public MenuGUI()
{
initUI();
}
public void initUI()
{
JMenuBar menubar = new JMenuBar();
Imag开发者_如何学运维eIcon icon = new ImageIcon(getClass().getResource("exit.png"));
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem = new JMenuItem("Exit", icon);
eMenuItem.setMnemonic(KeyEvent.VK_C);
eMenuItem.setToolTipText("Exit application");
eMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
file.add(eMenuItem);
menubar.add(file);
setJMenuBar(menubar);
setTitle("Simple menu");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
I can compile the code without problems, but I get a runtime exception:
Do you have the picture in the right directory? In your code you try load an icon and when it not exist, you get a NullPointerException
ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));
Otherwise comment it out, and create the menu item without an icon
JMenuItem eMenuItem = new JMenuItem("Exit");
Your problem is on the loading of the ImageIcon. Since no image is found at the correct folder, you are getting a nullpointer exception. The solution is simple: place the "exit.png" image in the same folder as your compiled class file.
精彩评论