Thursday, May 21, 2009

Learn how to create Menu in Swing

import java.awt.*;import java.awt.event.*;
import javax.swing.*;import java.util.*;import java.io.*;import java.util.*;import java.lang.*;

public class JZip {

public Container createContentPane() {
//Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);

//Create a scrolled text area.
JTextArea output = new JTextArea(5, 30);
output.setEditable(false);
JScrollPane scrollPane = new JScrollPane(output);

//Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}

public JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenuItem menuItem;
JRadioButtonMenuItem rbMenuItem;
JCheckBoxMenuItem cbMenuItem;

//Create the menu bar.
menuBar = new JMenuBar();

//Build the first menu.
JMenu fileMenu = new JMenu( "File");
JMenu editMenu = new JMenu("Edit");
JMenu exitMenu = new JMenu("Exit");

fileMenu.setMnemonic(KeyEvent.VK_F);
fileMenu.getAccessibleContext().setAccessibleDescription("This is Description");
exitMenu.setMnemonic(KeyEvent.VK_X);

JMenuItem fileNewMenuItem = new JMenuItem("New", KeyEvent.VK_N);
JMenuItem fileOpenMenuItem = new JMenuItem("Open", KeyEvent.VK_N);

fileMenu.add(fileNewMenuItem);
fileMenu.add(fileOpenMenuItem);

menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(exitMenu);
return menuBar;
}

/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Jzip");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.
JZip mainGUI = new JZip();
frame.setJMenuBar(mainGUI.createMenuBar());
frame.setContentPane(mainGUI.createContentPane());

//Display the window.
frame.setSize(450, 260);
frame.setVisible(true);
}

public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

No comments: