[Java Swing] - How to create a Menu Bar in Java UI.
Wednesday, November 29, 2017
Note: Some resources I get from Oracle: https://docs.oracle.com/javase/tutorial/uiswing/components/menu.html
Before create a menu in Java UI, we need to know the menu component hierarchy as below:
We must be created three objects: JMenuBar, JMenuItem, JMenu.
This section I use WindowBuilder tool on Eclipse Market.My purpose is convenience on control UI but I think you should handle fundamental about Java UI before use tool.
I. Install WindowBuilder
1. Go to menu bar > Help > Eclipse Market2. Search "WindowBuilder" keyword
3. Choose WindowBuilder x.x.x and install it.
4. Project > New > WindowBuilder > Swing Designer > Application Window
II. Examples About Menu on Java UI.
1. Create simple menuMenuOneDemo.java
package com.parentralcontrol.ui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JPanel;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
/**
* DESCRIPTION GOES HERE<br>
* @author Tri Ho
* @created Oct 28, 2017
* @version $Revision$
*/
public class MenuOneDemo {
private JFrame frmSimpleMenu;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MenuOneDemo window = new MenuOneDemo();
window.frmSimpleMenu.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MenuOneDemo() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmSimpleMenu = new JFrame();
frmSimpleMenu.setTitle("Simple Menu 1");
frmSimpleMenu.setBounds(100, 100, 450, 300);
frmSimpleMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmSimpleMenu.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 434, 55);
frmSimpleMenu.getContentPane().add(panel);
panel.setLayout(null);
//create a menu bar
JMenuBar menuBar = new JMenuBar();
menuBar.setBounds(0, 0, 97, 21);
panel.add(menuBar);
//create main menu
JMenu menu1 = new JMenu("Menu1");
JMenu menu2 = new JMenu("Menu3");
//add menu to menu bar
menuBar.add(menu1);
menuBar.add(menu2);
// create menu item
JMenuItem menuItem1 = new JMenuItem("Menu Item 1");
JMenuItem menuItem2 = new JMenuItem("Menu Item 2");
JMenuItem menuItem3 = new JMenuItem("Menu Item 3");
JMenuItem menuItem4 = new JMenuItem("Menu Item 4");
menu1.add(menuItem1);
menu1.add(menuItem2);
menu1.add(menuItem3);
menu2.add(menuItem4);
}
}
Results:
Bài liên quan
Comments[ 0 ]
Post a Comment