I'm creating menu bar and sub menus by using composite pattern. here is the code i took from internet but problem is I've no TestMenuFrame class. i'm beginner in design patterns. here is code: MenuBar.java
public class MenuBar extends JComponent {
public MenuBar() {
setLayout(new FlowLayout(FlowLayout.LEFT, 2, 2));
}
void addMainMenu(MenuComponent mainMenu) {
JButton btn = new JButton(mainMenu.getName());
final JPopupMenu popupMenu = new JPopupMenu();
Iterator<MenuComponent> iterator = mainMenu.iterator();
if (iterator != null) {
while (iterator.hasNext()) {
MenuComponent menuComponent = iterator.next();
JMenuItem item = new JMenuItem(menuComponent.getName());
popupMenu.add(item);
}
}
btn.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
JButton btn = (JButton) e.getSource();
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
add(btn);
}
}
MenuComponent.java
public abstract class MenuComponent {
protected String name;
public MenuComponent(String name) {
this.name = name;
}
public String getName() {
return name;
}
public abstract void addMenu(MenuComponent menu);
public abstract Iterator<MenuComponent> iterator();
}
MyMenu.java
public class MyMenu extends MenuComponent {
private List<MenuComponent> listMenu = new ArrayList<>();
public MyMenu(String name) {
super(name);
}
public void addMenu(MenuComponent menu) {
listMenu.add(menu);
}
public Iterator<MenuComponent> iterator() {
return listMenu.iterator();
}
}
MyMenuItem.java
public class MyMenuItem extends MenuComponent {
public MyMenuItem(String name) {
super(name);
}
public void addMenu(MenuComponent menu) {
// throw new UnsupportedOperationException("Not supported yet.");
}
public Iterator<MenuComponent> iterator() {
// throw new UnsupportedOperationException("Not supported yet.");
return null;
}
}
TestMenu.java
public static void main(String[] args) {
MenuComponent openMenu = new MyMenu("Open Menu");
MenuComponent openMenuItem1 = new MyMenuItem("Open Menu Item 1");
MenuComponent openMenuItem2 = new MyMenuItem("Open Menu Item 2");
openMenu.addMenu(openMenuItem1);
openMenu.addMenu(openMenuItem2);
MenuComponent exitMenuItem = new MyMenuItem("Exit Menu");
MenuComponent mainMenu = new MyMenu("Main");
mainMenu.addMenu(openMenu);
mainMenu.addMenu(exitMenuItem);
**TestMenuFrame frame = new TestMenuFrame();
frame.getMyMenuBar().addMainMenu(mainMenu);
frame.setVisible(true);**
}
i just need TestMenuFrame class. whose object was created in main.
Aucun commentaire:
Enregistrer un commentaire