【发布时间】:2014-05-14 21:58:37
【问题描述】:
我是相当新的Java编程。我创建了一个JMenu 并添加了actionlisten,但它没有触发。 JPanel、jpCommentMainPane 被添加到 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;
}
【问题讨论】:
-
我认为你需要将ActionListeners添加到JMenuItems,而不是JMenus。