Java tutorial
//package com.java2s; // it under the terms of the GNU General Public License as published by import java.awt.Component; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JSeparator; import javax.swing.MenuElement; public class Main { static final String NEWLINE = System.lineSeparator(); private static void appendMenuItem(Component menuItem, StringBuilder builder, String indent) { if (menuItem instanceof JMenuBar) { appendMenuSubElements((MenuElement) menuItem, builder, indent); } else if (menuItem instanceof JPopupMenu) { appendMenuSubElements((MenuElement) menuItem, builder, indent); } else if (menuItem instanceof JMenuItem) { builder.append(NEWLINE); builder.append(indent); builder.append(((JMenuItem) menuItem).getText()); builder.append(((JMenuItem) menuItem).isEnabled() ? "" : "[Disabled]"); appendMenuSubElements((JMenuItem) menuItem, builder, "| " + indent); } else if (menuItem instanceof JSeparator) { builder.append(NEWLINE); builder.append(indent); builder.append("--------"); } } private static void appendMenuSubElements(MenuElement element, StringBuilder builder, String indent) { for (MenuElement subItem : element.getSubElements()) { appendMenuItem((Component) subItem, builder, indent); } } }