Sunday, September 4, 2011

Creating a JMenuBar with JMenu and Mnemonics

Program Description:

One of the interesting part in programming java that I enjoyed the most is making JMenu, JMenuBar, and JMenuItem because it looks good in the program and it helps you manage and organize everything that is in your program. It is considered as one of the important part of a software. What I like about making JMenu, JMenuBar, and JMenuItem in Java is that it is very easy to create and understand.

Output:
Code:

/**

* File: menuBarWithMenu.java

* Tiltle: Creating a JMenuBar with JMenu and Mnemonics

* Author: http://java-code-complete.blogspot.com/

*/



//Java Core Package

import javax.swing.*;

//Java Extension Package

import java.awt.*;



public class menuBarWithMenu extends JFrame {



//Initializing JMenu, JMenuBar, Mnemonics, and Specified Menu Strings

private String menuNames[] = {"File","Edit","View","Project","Build","Run","Tools","Configure","Window","Help"};

private char mnemonic[] = {'F','E','V','P','B','R','T','C','W','H'};

private JMenu fileMenu[];

private JMenuBar menuBar;



//Setting up GUI

public menuBarWithMenu() {



//Setting up the Title of the Window

super("Creating a JMenuBar with JMenu and Mnemonics");



//Set Size of the Window (WIDTH, HEIGHT)

setSize(500,200);



//Exit Property of the Window

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);



//Constructing JMenu and JMenuBar

fileMenu = new JMenu[10];

menuBar = new JMenuBar();



//Setting up the JMenuBar in the container or automtically add JMenuBar in the container

setJMenuBar(menuBar);



//Constructing 10 JMenu using "for loop" with Mnemonics and automatically add it in the JMenuBar

for(int count=0; count<fileMenu.length; count++) {

fileMenu[count] = new JMenu(menuNames[count]); //Constructing JMenu using the specified strings above

fileMenu[count].setMnemonic(mnemonic[count]); //Adding mnemonics on JMenu using the specified characters above

menuBar.add(fileMenu[count]); //Adding all 10 JMenu in the JMenuBar

}



//Setting up the container ready for the components to be added.

Container pane = getContentPane();

setContentPane(pane);



/**Set all the Components Visible.

* If it is set to "false", the components in the container will not be visible.

*/

setVisible(true);

}



//Main Method

public static void main (String[] args) {

menuBarWithMenu mbwm = new menuBarWithMenu();

}

}

No comments:

Post a Comment