简体   繁体   English

如何将ActionListener添加到AWT MenuItem?

[英]How to add a ActionListener to the AWT MenuItem?

Thanks for your attention! 感谢您的关注! PLease help a newbie out :) 请帮助新手:)

Current Problem: 当前问题:

Need to change a color of the line when clicking on a MenuItem with the name of the color. 单击带有颜色名称的MenuItem时需要更改线条的颜色。

Here is my code for changing the color of the line. 这是我用于更改线条颜色的代码。 When i create the menuItems i also crete the actionListener for them: 当我创建menuItems时,我也为它们创建了actionListener:

private void CreateMenu()
{
    menuBar = new MenuBar();
    menu = new Menu("File");
    mSave = new MenuItem("Save");
    colorSubMenu = new Menu("Choose Color...");

    String[] colors = {"red","yellow","green","blue","purple","black"};
    for(int i=0;i<colors.length;i++)
    {
        final int ii = i;
        MenuItem m=new MenuItem(colors[i]);
        colorSubMenu.add(m);
        colorSubMenu.addActionListener(
                                    new ActionListener()
                                            {
                                                @Override public void actionPerformed(ActionEvent e)
                                                {
                                       THIS LINE DOESN'T WORK ===>> color = Color.getColor(colorSubMenu.getItem(ii)));
                                                }
                                             }
                                        );
    }

    menu.add(mSave);        
    menu.add(colorSubMenu);
    menuBar.add(menu);        
    setMenuBar(menuBar);
}

But... it doesn't work! 但是...这不起作用! please give an advise. 请给个建议。 i am running out of ideas. 我的想法不多了。

Will be glad to hear anything:) thanks once again! 会很高兴听到任何消息:)再次感谢!

UPDATE: 更新:

want to change this part to something more elegant and that actually works: 想要将此部分更改为更优雅的东西,并且确实有效:

colorSubMenu.addActionListener(
   new ActionListener()
   {
      @Override 
      public void actionPerformed(ActionEvent e)
      {
THIS LINE DOESN'T WORK ===>> color = Color.getColor(colorSubMenu.getItem(ii)));
      }
   }
);

Color#getColor relys on using colors from the System properties. Color#getColor依赖于使用系统属性中的颜色。 These probably will not match the colors from the Color array in the question. 这些可能与问题中Color数组中的颜色不匹配。 You can use reflection instead 您可以改用反射

@Override
public void actionPerformed(ActionEvent e) {
    Field field = Class.forName ("java.awt.Color").getField (e.getActionCommand());
    Color color = (Color) field.get (null);
    // use color...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM