Java Swing - Adding JMenuBar to a Child Panel Container [Updated: Dec 14, 2017, Created: Dec 14, 2017] |
|
||
This example shows how to add JMenuBar to a child container panel. We just need to add Examplepublic class ContainerWithMenuBarExample { public static void main(String[] args) { JFrame frame = createFrame(); //child container with menu frame.add(createContainerWithMenu(), BorderLayout.EAST); //others frame.add(createLabel("Tool Container", Color.LIGHT_GRAY), BorderLayout.NORTH); frame.add(createLabel("left container", Color.CYAN.darker()), BorderLayout.WEST); frame.add(createLabel("center container", Color.WHITE), BorderLayout.CENTER); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static Component createContainerWithMenu() { JRootPane rootPane = new JRootPane(); rootPane.getContentPane().add(createLabel("Right container", Color.PINK)); JMenuBar menuBar = new JMenuBar(); menuBar.add(createMenu("File", "Open", "Close", "New", "Exit")); menuBar.add(createMenu("Edit", "Cut", "Copy", "Paste")); menuBar.add(createMenu("View", "view 1", "view 2")); menuBar.add(createMenu("Help", "help 1", "help 2")); rootPane.setJMenuBar(menuBar); return rootPane; } private static JMenu createMenu(String menuLabel, String... subMenuLabels) { JMenu menu = new JMenu(menuLabel); for (String subMenuLabel : subMenuLabels) { JMenuItem menuItem = new JMenuItem(subMenuLabel); menu.add(menuItem); } return menu; } private static JLabel createLabel(String text, Color color) { JLabel label = new JLabel(text, SwingConstants.CENTER); label.setOpaque(true); label.setBackground(color); return label; } private static JFrame createFrame() { JFrame frame = new JFrame("Panel with JMenuBar Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(new Dimension(400, 300)); return frame; } } Output![]() Example ProjectDependencies and Technologies Used:
|
|
||
|
|||
|
|||
|