Menus and toolbars in Java Swing
A menubar is one of the most visible parts of the GUI application. It is a group of commands located in various menus. While in console applications you had to remember all those arcane commands, here we have most of the commands grouped into logical parts. There are accepted standards that further reduce the amount of time spending to learn a new application.In Java Swing, to implement a menubar, we use three objects. A
JMenuBar
, a JMenu
and a JMenuItem
. Simple menu
We begin with a simple menubar example.package zetcode;Our example will show a menu with one item. Selecting the exit menu item we close the application.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
public class Example extends JFrame {
public Example() {
initUI();
}
public final void initUI() {
JMenuBar menubar = new JMenuBar();
ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem = new JMenuItem("Exit", icon);
eMenuItem.setMnemonic(KeyEvent.VK_C);
eMenuItem.setToolTipText("Exit application");
eMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
file.add(eMenuItem);
menubar.add(file);
setJMenuBar(menubar);
setTitle("Simple menu");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Example ex = new Example();
ex.setVisible(true);
}
});
}
}
JMenuBar menubar = new JMenuBar();Here we create a menubar.
ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));We will display an icon in the menu.
JMenu file = new JMenu("File");We create a menu object. The menus can be accessed via the keybord as well. To bind a menu to a particular key, we use the
file.setMnemonic(KeyEvent.VK_F);
setMnemonic()
method. In our case, the menu can be opened with the ALT + F shortcut. fileClose.setToolTipText("Exit application");This code line creates a tooltip for a menu item.
Figure: Simple menu
Submenu
Each menu can also have a submenu. This way we can group similar commnads into groups. For example we can place commands that hide/show various toolbars like personal bar, address bar, status bar or navigation bar into a submenu called toolbars. Within a menu, we can seperate commands with a separator. It is a simple line. It is common practice to separate commands like new, open, save from commands like print, print preview with a single separator. Menus commands can be launched via keyboard shortcuts. For this, we define menu item accelerators.package zetcode;In this example, we create a submenu, a menu separator and an accelerator key.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class Example extends JFrame {
public Example() {
initUI();
}
public final void initUI() {
JMenuBar menubar = new JMenuBar();
ImageIcon iconNew = new ImageIcon(getClass().getResource("new.png"));
ImageIcon iconOpen = new ImageIcon(getClass().getResource("open.png"));
ImageIcon iconSave = new ImageIcon(getClass().getResource("save.png"));
ImageIcon iconExit = new ImageIcon(getClass().getResource("exit.png"));
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenu imp = new JMenu("Import");
imp.setMnemonic(KeyEvent.VK_M);
JMenuItem newsf = new JMenuItem("Import newsfeed list...");
JMenuItem bookm = new JMenuItem("Import bookmarks...");
JMenuItem mail = new JMenuItem("Import mail...");
imp.add(newsf);
imp.add(bookm);
imp.add(mail);
JMenuItem fileNew = new JMenuItem("New", iconNew);
fileNew.setMnemonic(KeyEvent.VK_N);
JMenuItem fileOpen = new JMenuItem("Open", iconOpen);
fileNew.setMnemonic(KeyEvent.VK_O);
JMenuItem fileSave = new JMenuItem("Save", iconSave);
fileSave.setMnemonic(KeyEvent.VK_S);
JMenuItem fileExit = new JMenuItem("Exit", iconExit);
fileExit.setMnemonic(KeyEvent.VK_C);
fileExit.setToolTipText("Exit application");
fileExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
ActionEvent.CTRL_MASK));
fileExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
file.add(fileNew);
file.add(fileOpen);
file.add(fileSave);
file.addSeparator();
file.add(imp);
file.addSeparator();
file.add(fileExit);
menubar.add(file);
setJMenuBar(menubar);
setTitle("Submenu");
setSize(360, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Example ex = new Example();
ex.setVisible(true);
}
});
}
}
JMenu imp = new JMenu("Import");A submenu is just like any other normal menu. It is created the same way. We simply add a menu to existing menu.
...
file.add(imp);
fileExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,An accelerator is a key shortcut that launches a menu item. In our case, by pressing Ctrl + W we close the application.
ActionEvent.CTRL_MASK));
file.addSeparator();A separator is a horizontal line that visually separates the menu items. This way we can group items into some logical places.
Figure: Submenu
JCheckBoxMenuItem
A menu item that can be selected or deselected. If selected, the menu item typically appears with a checkmark next to it. If unselected or deselected, the menu item appears without a checkmark. Like a regular menu item, a check box menu item can have either text or a graphic icon associated with it, or both.package zetcode;The example shows a
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;
public class Example extends JFrame {
private JLabel statusbar;
public Example() {
initUI();
}
public final void initUI() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenu view = new JMenu("View");
view.setMnemonic(KeyEvent.VK_V);
JCheckBoxMenuItem sbar = new JCheckBoxMenuItem("Show StatuBar");
sbar.setState(true);
sbar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (statusbar.isVisible()) {
statusbar.setVisible(false);
} else {
statusbar.setVisible(true);
}
}
});
view.add(sbar);
menubar.add(file);
menubar.add(view);
setJMenuBar(menubar);
statusbar = new JLabel(" Statusbar");
statusbar.setBorder(BorderFactory.createEtchedBorder(
EtchedBorder.RAISED));
add(statusbar, BorderLayout.SOUTH);
setTitle("JCheckBoxMenuItem");
setSize(360, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Example ex = new Example();
ex.setVisible(true);
}
});
}
}
JCheckBoxMenuItem
. By selecting the menu item, we toggle the visibility of the statusbar. JCheckBoxMenuItem sbar = new JCheckBoxMenuItem("Show StatuBar");We create the
sbar.setState(true);
JCheckBoxMenuItem
and check it by default. The statusbar is initially visible. if (statusbar.isVisible()) {Here we toggle the visibility of the statusbar.
statusbar.setVisible(false);
} else {
statusbar.setVisible(true);
}
statusbar = new JLabel(" Statusbar");The statusbar is a simple
statusbar.setBorder(BorderFactory.createEtchedBorder(
EtchedBorder.RAISED));
JLabel
component. We put a raised EtchedBorder
around the label, so that it is visible. Figure: JCheckBoxMenuItem
A popup menu
Another type of a menu is a popup menu. It is sometimes called a context menu. It is usually shown, when we right click on a component. The idea is to provide only the commands, that are relevant to the current context. Say we have an image. By right clicking on the image, we get a window with commands to save, rescale, move etc the image.package zetcode;Our example shows a demonstrational popup menu with two commands. The first option of the popup menu will beep a sound, the second one will close the window.
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
public class PopupMenu extends JFrame
{
private JPopupMenu menu;
private Toolkit toolkit;
public PopupMenu(String title)
{
super(title);
this.initUI();
}
private void initUI()
{
toolkit = this.getToolkit();
menu = new JPopupMenu();
JMenuItem menuItemBeep = new JMenuItem("Beep");
menuItemBeep.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
toolkit.beep();
}
});
menu.add(menuItemBeep);
JMenuItem menuItemClose = new JMenuItem("Close");
menuItemClose.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
menu.add(menuItemClose);
this.addMouseListener(new MouseAdapter()
{
@Override
public void mouseReleased(MouseEvent e)
{
if (e.getButton() == MouseEvent.BUTTON3)
{
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(250, 200);
this.setLocationRelativeTo(null);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
PopupMenu pm = new PopupMenu("JPopupMenu");
pm.setVisible(true);
}
});
}
}
In our example, we create a submenu, menu separators and create an accelerator key.
menu = new JPopupMenu();To create a popup menu, we have a class called
JPopupMenu
. JMenuItem menuItemBeep = new JMenuItem("Beep");The menu item is the same, as with the standard
JMenu
this.addMouseListener(new MouseAdapter()The popup menu is shown, where we clicked with the mouse button. The MouseEvent.BUTTON3 constant is here to enable the popup menu only for the mouse right click.
{
@Override
public void mouseReleased(MouseEvent e)
{
if (e.getButton() == MouseEvent.BUTTON3)
{
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
Figure: Popup menu
JToolbar
Menus group commands that we can use in an application. Toolbars provide a quick access to the most frequently used commands. In Java Swing, theJToolBar
class creates a toolbar in an application. package zetcode;The example creates a toolbar with one exit button.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
public class Example extends JFrame {
public Example() {
initUI();
}
public final void initUI() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
menubar.add(file);
setJMenuBar(menubar);
JToolBar toolbar = new JToolBar();
ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));
JButton exitButton = new JButton(icon);
toolbar.add(exitButton);
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
add(toolbar, BorderLayout.NORTH);
setTitle("Simple toolbar");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Example ex = new Example();
ex.setVisible(true);
}
});
}
}
JToolBar toolbar = new JToolBar();This is the
JToolBar
constructor. JButton exitButton = new JButton(icon);We create a button and add it to the toolbar.
toolbar.add(exitButton);
Figure: Simple toolbar
Toolbars
Say, we wanted to create two toolbars. The next example shows, how we could do it.package zetcode;We show only one way, how we could create toolbars. Of course, there are several possibilities. We put a
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
public class Example extends JFrame {
public Example() {
initUI();
}
public final void initUI() {
JToolBar toolbar1 = new JToolBar();
JToolBar toolbar2 = new JToolBar();
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
ImageIcon newi = new ImageIcon(
getClass().getResource("new.png"));
ImageIcon open = new ImageIcon(
getClass().getResource("open.png"));
ImageIcon save = new ImageIcon(
getClass().getResource("save.png"));
ImageIcon exit = new ImageIcon(
getClass().getResource("exit.png"));
JButton newb = new JButton(newi);
JButton openb = new JButton(open);
JButton saveb = new JButton(save);
toolbar1.add(newb);
toolbar1.add(openb);
toolbar1.add(saveb);
toolbar1.setAlignmentX(0);
JButton exitb = new JButton(exit);
toolbar2.add(exitb);
toolbar2.setAlignmentX(0);
exitb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
panel.add(toolbar1);
panel.add(toolbar2);
add(panel, BorderLayout.NORTH);
setTitle("Toolbars");
setSize(360, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Example ex = new Example();
ex.setVisible(true);
}
});
}
}
JPanel
to the north of the BorderLayout
manager. The panel has a vertical BoxLayout
. We add the two toolbars into this panel. JToolBar toolbar1 = new JToolBar();Creation of two toolbars.
JToolBar toolbar2 = new JToolBar();
JPanel panel = new JPanel();The panel has a vertical
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
BoxLayout
. toolbar1.setAlignmentX(0);The toolbar is left aligned.
panel.add(toolbar1);We add the toolbars to the panel. Finally, the panel is located into the north part of the frame.
panel.add(toolbar2);
add(panel, BorderLayout.NORTH);
Figure: Toolbars
In this part of the Java Swing tutorial, we have mentioned menus and toolbars.
No comments:
Post a Comment