Link JMenu and JToolBar in Java

Description

The following code shows how to link JMenu and JToolBar.

Example


//  w  w  w  .  ja  v a  2  s . co m
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O'Reilly 
*/
// MenuActionExample.java
//This example create a menubar and toolbar both populated with Action
//objects.
//

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;

public class Main extends JPanel {

  public JMenuBar menuBar;

  public JToolBar toolBar;

  public Main() {
    super(true);

    // Create a menu bar and give it a bevel border.
    menuBar = new JMenuBar();

    // Create a menu and add it to the menu bar.
    JMenu menu = new JMenu("Menu");
    menuBar.add(menu);

    // Create a toolbar and give it an etched border.
    toolBar = new JToolBar();

    // Instantiate a sample action with the NAME property of
    // "Download" and the appropriate SMALL_ICON property.
    SampleAction exampleAction = new SampleAction("Download",
        new ImageIcon("action.gif"));


    JMenuItem exampleItem = new JMenuItem(exampleAction);
    JButton exampleButton = new JButton(exampleAction);
    menu.add(exampleItem);
    toolBar.add(exampleButton);
  }

  class SampleAction extends AbstractAction {
    // This is our sample action. It must have an actionPerformed() method,
    // which is called when the action should be invoked.
    public SampleAction(String text, Icon icon) {
      super(text, icon);
    }

    public void actionPerformed(ActionEvent e) {
      System.out.println("Action [" + e.getActionCommand()
          + "] performed!");
    }
  }

  public static void main(String s[]) {
    Main example = new Main();
    JFrame frame = new JFrame("Action Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setJMenuBar(example.menuBar);
    frame.getContentPane().add(example.toolBar, BorderLayout.NORTH);
    frame.setSize(200, 200);
    frame.setVisible(true);
  }
}

The code above generates the following result.

Link JMenu and JToolBar in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer