除子菜单外,我的代码工作正常。 “导入”按钮应该扩展为新闻源,书签和邮件。但是,该程序甚至不显示“导入”。它显示第一个不能悬停的子菜单条目(“newsfeed”)。我做错了什么?
import javax.swing.*;
import java.awt.event.*;
public class test extends JFrame{
private static final long serialVersionUID = 1L;
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
test ex = new test();
ex.setVisible(true);
}
});
}
public test()
{
initGUI();
}
public final void initGUI()
{
JMenuBar menubar = new JMenuBar();
ImageIcon exitIcon = new ImageIcon("icons/exit.png");
ImageIcon openIcon = new ImageIcon("icons/open.png");
ImageIcon newIcon = new ImageIcon("icons/new.png");
ImageIcon saveIcon = new ImageIcon("icons/save.png");
JMenu file = new JMenu("File");
JMenuItem importMenu = new JMenuItem("Import");
importMenu.setMnemonic(KeyEvent.VK_M);
JMenuItem newsfeedMenu = new JMenuItem("Import newsfeed list...");
JMenuItem bookmarksMenu = new JMenuItem("Import bookmarks...");
JMenuItem mailMenu = new JMenuItem("Import mail...");
importMenu.add(newsfeedMenu);
importMenu.add(bookmarksMenu);
importMenu.add(mailMenu);
JMenuItem newMenu = new JMenuItem("New", newIcon);
newMenu.setMnemonic(KeyEvent.VK_N);
newMenu.setToolTipText("Start new document");
JMenuItem openMenu = new JMenuItem("Open", openIcon);
openMenu.setMnemonic(KeyEvent.VK_O);
openMenu.setToolTipText("Open document");
JMenuItem saveMenu = new JMenuItem("Save", saveIcon);
saveMenu.setMnemonic(KeyEvent.VK_S);
saveMenu.setToolTipText("Save document");
JMenuItem exitMenu = new JMenuItem("Exit", exitIcon);
exitMenu.setMnemonic(KeyEvent.VK_X);
exitMenu.setToolTipText("Exit application");
exitMenu.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
System.exit(0);
}
});
exitMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
KeyEvent.CTRL_MASK));
file.add(newMenu);
file.add(openMenu);
file.add(saveMenu);
file.addSeparator();
file.add(importMenu);
file.addSeparator();
file.add(exitMenu);
menubar.add(file);
setJMenuBar(menubar);
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
JButton button = new JButton("Quit");
button.setBounds(100,60,80,40);
button.setToolTipText("Press");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
System.exit(0);
}
});
panel.add(button);
setSize(300, 200);
setTitle("testGUI");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
答案 0 :(得分:5)
将其更改为JMenu
JMenu importMenu = new JMenu("Import");