I am fairly new java programming. I created a JMenu
and add the actionlisten
, but it didn't fire. The JPanel
, jpCommentMainPane
, is added to JFrame
. Also the JFrame
has its own menu bar and actionlistener
. Would someone tell me how to make it work. Thanks in advance.
There is my code to add the JMenu
into the 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);
There is the method to return the 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;
}
JMenus need MenuListeners not ActionListeners to handle events. JMenuItems will use ActionListeners , however I'm not sure about JRadioButtonMenuItems.
One thing to try would be using inner classes for each JRadioButtonMenuItem.
For example, for the menuItemType
public class menuItemTypeListener implements ActionListener{
public void ActionPerformed(ActionEvent ae){
//Do Something here
}
}
menuItemType.addActionListener(new menuItemTypeListener());