001package jmri.jmrit.display; 002 003import java.awt.event.ActionListener; 004import java.beans.PropertyChangeEvent; 005import java.beans.PropertyChangeListener; 006import java.util.Comparator; 007import java.util.ServiceLoader; 008import java.util.Set; 009import java.util.stream.StreamSupport; 010import javax.annotation.CheckForNull; 011import javax.swing.JMenu; 012import javax.swing.JMenuItem; 013import jmri.InstanceManager; 014 015/** 016 * Create the "Panels" menu for use in a menubar. 017 * 018 * @author Bob Jacobsen Copyright 2003, 2004, 2010 019 * @author Dave Duchamp Copyright 2007 020 * @author Pete Cressman Copyright 2010 021 */ 022public class PanelMenu extends JMenu { 023 024 private JMenu panelsSubMenu = null; 025 private JMenuItem noPanelsItem = null; 026 private final PropertyChangeListener listener = this::updateMenu; 027 028 /** 029 * The single PanelMenu must accessed using 030 * {@link jmri.InstanceManager#getDefault(java.lang.Class)}. 031 */ 032 public PanelMenu() { 033 034 super.setText(Bundle.getMessage("MenuPanels")); 035 036 // new panel is a submenu 037 //add(new jmri.jmrit.display.NewPanelAction()); 038 JMenu newPanel = new JMenu(Bundle.getMessage("MenuItemNew")); 039 StreamSupport.stream(ServiceLoader.load(EditorActionFactory.class).spliterator(), false) 040 .sorted(Comparator.comparing(EditorActionFactory::getTitle)) 041 .forEach(factory -> newPanel.add(factory.createAction())); 042 super.add(newPanel); 043 044 panelsSubMenu = new JMenu(Bundle.getMessage("MenuShowPanel")); 045 // Add the 'No Panels' item to the sub-menu 046 noPanelsItem = new JMenuItem(Bundle.getMessage("MenuItemNoPanels")); 047 noPanelsItem.setEnabled(false); 048 panelsSubMenu.add(noPanelsItem); 049 super.add(panelsSubMenu); 050 051 super.add(new jmri.jmrit.display.PanelDeleteAction(Bundle.getMessage("MenuItemDeletePanel"))); // NOI18N 052 053 InstanceManager.getDefault(EditorManager.class).addPropertyChangeListener(listener); 054 updateMenu(null); 055 } 056 057 private void updateMenu(@CheckForNull PropertyChangeEvent evt) { 058 Set<Editor> editors = InstanceManager.getDefault(EditorManager.class).getAll(); 059 panelsSubMenu.removeAll(); 060 if (editors.isEmpty()) { 061 panelsSubMenu.add(noPanelsItem); 062 this.getItem(2).setEnabled(false); // Disable Delete Panel... 063 } else { 064 this.getItem(2).setEnabled(true); // Enable Delete Panel... 065 editors.forEach(editor -> { 066 JMenuItem menuItem = new JMenuItem(editor.getTitle()); 067 ActionListener action = event -> { 068 editor.getTargetFrame().setVisible(true); 069 editor.getTargetFrame().repaint(); 070 }; 071 menuItem.addActionListener(action); 072 panelsSubMenu.add(menuItem); 073 }); 074 } 075 } 076 077}