有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java ActionListen没有在JMenu上启动

我对java编程相当陌生。我创建了一个JMenu并添加了actionlisten,但它没有启动。JPaneljpCommentMainPane被添加到JFrame。另外JFrame有自己的菜单栏和actionlistener。有人能告诉我怎么做吗。提前谢谢

下面是我将JMenu添加到JPanel的代码:

jpCommentMainPane=new JPanel();         
jpCommentMainPane.setLayout(new BorderLayout(10,10));
JPanel totalCommentPane=new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel jpFindPane=new JPanel(new FlowLayout(FlowLayout.LEFT));      
totalCommentPane.setPreferredSize(new Dimension(rightPaneWidth,20));        
jpFindPane.add(sortMenu());  //add menubar
JPanel topPane=new JPanel();
topPane.setLayout(new BorderLayout());
topPane.add(jpFindPane, BorderLayout.SOUTH);
jpCommentMainPane.add(topPane, BorderLayout.NORTH);

有一种方法可以返回JMenuBar

//Create sort menu bar
private JMenuBar sortMenu(){

    JMenuBar menuBar=new JMenuBar();
    JMenu menu=new JMenu("Sort");
    JRadioButtonMenuItem menuItemType=new JRadioButtonMenuItem("Type");
    menu.add(menuItemType);
    JRadioButtonMenuItem menuItemPage=new  JRadioButtonMenuItem("Page");
    menu.add(menuItemPage);
    JRadioButtonMenuItem menuItemAuthor=new  JRadioButtonMenuItem("Author");
    menu.add(menuItemAuthor);
    JRadioButtonMenuItem menuItemDate=new  JRadioButtonMenuItem("Date");
    menu.add(menuItemDate);
    menu.addActionListener(new ActionListener(){            
    @Override
        public void actionPerformed(ActionEvent e){ 
             Utility.DisplayErrorMsg(pageErrorPrefix+ "line 145");
            String command=e.getActionCommand().trim().toUpperCase();
            if (command.equals(SortItem.TYPE)){
                pageSortBy=SortItem.TYPE;
            }else if (command.equals(SortItem.PAGE)){
                pageSortBy=SortItem.PAGE;
            }else if(command.equals(SortItem.TYPE)){
                pageSortBy=SortItem.TYPE;
            }else if(command.equals(SortItem.CREATOR)){
                pageSortBy=SortItem.CREATOR;
            }else if (command.equals(SortItem.DATE)){
                pageSortBy=SortItem.DATE;
            }

            getListCommentPane();

        }

    }

            );
    menuBar.add(menu);
    return menuBar;


}

共 (2) 个答案

  1. # 1 楼答案

    好吧,我现在确定了。可以将ActionListener添加到JMenu,但与JMenuItem不同,它没有效果。相反,如果JMenu对象需要侦听器,则应该向JMenu添加一个MenuListener

  2. # 2 楼答案

    JMenus需要MenuListener而不是ActionListener来处理事件。JMenuItems将使用ActionListeners,但我不确定JRadioButtonMenuItems是否正确

    可以尝试的一件事是为每个JRadioButtonMenuItem使用内部类

    例如,对于menuItemType

    public class menuItemTypeListener implements ActionListener{
         public void ActionPerformed(ActionEvent ae){
             //Do Something here
         }
    }
    
    menuItemType.addActionListener(new menuItemTypeListener());