import javax.swing.*;
import java.awt.event.*;
public class MenuTest extends JFrame{
JMenuBar menuBar=new JMenuBar();
JMenu menu=new JMenu("JMenu");
JMenuItem menuItem=new JMenuItem("JMenuItem");
public MenuTest(){
menu.add(menuItem);
menuBar.add(menu);
menuItem.addActionListener(new AL());
this.setJMenuBar(menuBar);
this.setAlwaysOnTop(true);
this.setTitle("LAFTest");
this.setSize(400,250);
this.setLocation(352,309);
this.setVisible(true);
this.setDefaultCloseOperation(3);
}
class AL implements ActionListener{
public void actionPerformed(ActionEvent e){
System.out.println("AL");
}
}
public static void main (String[] args) {
try {
     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception ex) {
ex.printStackTrace();
}
new MenuTest();
}
}
我想让上面的程序实现 alt +J 打开jmenu菜单再点击J执行item 并且 JMenu的J 加下划线,JMenultem的J也加下划线应如何实现呢?

解决方案 »

  1.   

    使用setMnemonic.
    public void setMnemonic(char mnemonic)
    This method is now obsolete, please use setMnemonic(int) to set the mnemonic for a button. This method is only designed to handle character values which fall between 'a' and 'z' or 'A' and 'Z'. JMenuItem menuItem=new JMenuItem("JMenuItem");
    menuItem.setMnemonic('J');同时小提示, 想使用快捷键功能, 如ctr + s为保存时, 可以使用:
    public void setAccelerator(KeyStroke keyStroke)
    Sets the key combination which invokes the menu item's action listeners without navigating the menu hierarchy. It is the UI's responsibility to install the correct action. Note that when the keyboard accelerator is typed, it will work whether or not the menu is currently displayed. Parameters:
    keyStroke - the KeyStroke which will serve as an acceleratorsetAccelerator is not defined for JMenu. Use setMnemonic instead. 这个功能只能用于JMenuItem