Link to home
Start Free TrialLog in
Avatar of Zolf
ZolfFlag for United Arab Emirates

asked on

menubar with picture


hello there,

i want to have a menubar with picture in it,something like a Jtoolbar but doing the function of a menu i.e
when clicked on it it should give options under it.for example on IE,they have used such a thing,but i want to do it in java.
please help.
cheers
zolf
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Add a JMenu to either a JToolBar or a JMenuBar. You can add pictures to menu items using the setIcon() method

http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/AbstractButton.html#setIcon(javax.swing.Icon)
Avatar of Zolf

ASKER


hi objects,

could you please give me some java example of doing this.
http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html

another thing you can do is use a popup menu that is activated by a button press
Avatar of Zolf

ASKER


your second suggestion is good,but can you help me how can i start to implement it with image on it.i shall appreciate your help
Avatar of Zolf

ASKER


I have done this but i dont get the popup menu

Icon icon = new ImageIcon("Images/NotePad.gif");
JButton button = new JButton(action);
 button.addActionListener (this);

Action action = new AbstractAction("Button Label", icon)
 {
   
        public void actionPerformed(ActionEvent evt)
 {
           System.out.println("Yes i am clicked");
           JPopupMenu popup;
           JMenuBar menuBar;
           JMenu menu, submenu;
           JMenuItem menuItem;
           //...where the GUI is constructed:
           //Create the popup menu.
           popup = new JPopupMenu();
           menuItem = new JMenuItem("A popup menu item");
           menuItem.addActionListener(this);
           popup.add(menuItem);
           menuItem = new JMenuItem("Another popup menu item");
           menuItem.addActionListener(this);
           popup.add(menuItem);
        }
    };
Avatar of Zolf

ASKER


this is the complete code.please help do to insert menu to the button

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.text.*;
import java.io.*;
import java.awt.PrintJob.*;
import javax.swing.plaf.metal.*;


public class DslamSystem extends JFrame implements ActionListener, ItemListener {

      //Main Place on Form where All Child Forms will Shown.
      private JDesktopPane desktop = new JDesktopPane ();
      
      ImageIcon[] images;
      String[] petStrings = {"NotePad", "Keys", "Help"};
      
      //For Program's MenuBar.
      private JMenuBar bar;

      //All the Main Menu of the Program.
      private JMenu mnuFile;

      private JMenuItem addNew, printRec, end;                        //File Menu Options.
      
      private JPopupMenu popMenu = new JPopupMenu ();

      //For Program's ToolBar.
      private      JToolBar toolBar;

      //For ToolBar's Button.
      private      JButton btnNew, btnDep, btnWith, btnRec, btnDel, btnSrch, btnHelp, btnKey;

      //Main Form StatusBar where Program's Name & Welcome Message Display.
      private JPanel statusBar = new JPanel ();

      //Labels for Displaying Program's Name & saying Welcome to Current User on StatusBar.
      private JLabel welcome;
      private JLabel author;

      //Making the LookAndFeel Menu.
      private String strings[] = {"1. Metal", "2. Motif", "3. Windows"};
      private UIManager.LookAndFeelInfo looks[] = UIManager.getInstalledLookAndFeels ();
      private ButtonGroup group = new ButtonGroup ();
      private JRadioButtonMenuItem radio[] = new JRadioButtonMenuItem[strings.length];

      //Getting the Current System Date.
      private java.util.Date currDate = new java.util.Date ();
      private SimpleDateFormat sdf = new SimpleDateFormat ("dd MMMM yyyy", Locale.getDefault());
      private String d = sdf.format (currDate);

      //Following all Variables are use in DslamSystem's IO's.

      //Variable use in Reading the DslamSystem Records File & Store it in an Array.
      private int count = 0;
      private int rows = 0;
      private      int total = 0;

      //String Type Array use to Load Records From File.
      private String records[][] = new String [500][6];

      Icon icon ;
      JButton button;
      //Constructor of Program to Iniatilize all Variables of Program.

      public DslamSystem () {

            //Setting Program's Title.
            super ("  ");

            //Setting the Main Window of Program.
            setIconImage (getToolkit().getImage ("Images/Bank.gif"));
            //setSize (700, 550);
            setJMenuBar (bar);

            //Closing Code of Main Window.
            addWindowListener (new WindowAdapter () {
                  public void windowClosing (WindowEvent we) {
                        quitApp ();
                  }
            }
            );

            //Setting the Location of Application on Screen.

            Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setSize(screenSize.width, screenSize.height - 30);
            
            mnuFile = new JMenu ("File");
            
            addNew = new JMenuItem ("Open New Account", new ImageIcon ("Images/Open.gif"));
            addNew.addActionListener (this);
            
            mnuFile.add (addNew);
            
            JMenuItem open = new JMenuItem ("Open New Account", new ImageIcon ("Images/Open.gif"));
            open.addActionListener (this);
            
            popMenu.add (open);
            
            //bar.add (mnuFile);
            button = new JButton(action);
            
             button.addActionListener (this);
            //Creating the ToolBar's Buttons of Program.
            btnNew = new JButton (new ImageIcon ("Images/NotePad.gif"));
            btnNew.setToolTipText ("        ");
            btnNew.addActionListener (this);
            btnDep = new JButton (new ImageIcon ("Images/ImationDisk.gif"));
            btnDep.setToolTipText ("           ");
            btnDep.addActionListener (this);
            btnWith = new JButton (new ImageIcon ("Images/SuperDisk.gif"));
            btnWith.setToolTipText ("       ");
            btnWith.addActionListener (this);
            btnRec = new JButton (new ImageIcon ("Images/Paproll.gif"));
            btnRec.setToolTipText ("          ");
            btnRec.addActionListener (this);
            btnDel = new JButton (new ImageIcon ("Images/Toaster.gif"));
            btnDel.setToolTipText ("        ");
            btnDel.addActionListener (this);
            btnSrch = new JButton (new ImageIcon ("Images/Search.gif"));
            btnSrch.setToolTipText ("           ");
            btnSrch.addActionListener (this);
            btnHelp = new JButton (new ImageIcon ("Images/Help.gif"));
            btnHelp.setToolTipText ("          ");
            btnHelp.addActionListener (this);
            btnKey = new JButton (new ImageIcon ("Images/Keys.gif"));
            btnKey.setToolTipText ("Shortcut Keys of DslamSystem");
            btnKey.addActionListener (this);
            
            images = new ImageIcon[petStrings.length];
            
        Integer[] intArray = new Integer[petStrings.length];
       
        for (int i = 0; i < petStrings.length; i++) {
            intArray[i] = new Integer(i);
            images[i] = createImageIcon("Images/" + petStrings[i] + ".gif");
            if (images[i] != null) {
                images[i].setDescription(petStrings[i]);
            }
        }
       
            //Creating the ToolBar of Program.
            toolBar = new JToolBar ();
            toolBar.add (btnNew);
            toolBar.addSeparator ();
            toolBar.add (btnDep);
            toolBar.add (btnWith);
            toolBar.addSeparator ();
            toolBar.add (btnRec);
            toolBar.addSeparator ();
            toolBar.add (btnDel);
            toolBar.addSeparator ();
            toolBar.add (btnSrch);
            toolBar.addSeparator ();            
            toolBar.add (button);
            
            //Creating the StatusBar of Program.
            author = new JLabel (" " + "    ", Label.LEFT);
            author.setForeground (Color.black);
            author.setToolTipText ("Program's Title");
            welcome = new JLabel ("Welcome Today is " + d + " ", JLabel.RIGHT);
            welcome.setForeground (Color.black);
            welcome.setToolTipText ("Welcoming the User & System Current Date");
            statusBar.setLayout (new BorderLayout());
            statusBar.add (author, BorderLayout.WEST);
            statusBar.add (welcome, BorderLayout.EAST);

            //For Making the Dragging Speed of Internal Frames Faster.
            desktop.putClientProperty ("JDesktopPane.dragMode", "outline");

            //Setting the Contents of Programs.
            getContentPane().add (toolBar, BorderLayout.NORTH);
            getContentPane().add (desktop, BorderLayout.CENTER);
            getContentPane().add (statusBar, BorderLayout.SOUTH);

            //Showing The Main Form of Application.
            setVisible (true);

      }

      /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = DslamSystem.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
                return null;
        }
    }


      Action action = new AbstractAction("Button Label", icon)
      {
        // This method is called when the button is pressed      

        public void actionPerformed(ActionEvent evt)
        {
              icon = new ImageIcon("Images/NotePad.gif");
              button.setIcon(icon);
              //button.setIcon(null);

        }
    };
      
      //Function For Performing different Actions By Menus of Program.

      public void actionPerformed (ActionEvent ae)
      {
            Object obj = ae.getSource();
            
            if (obj == end)
            {
                  quitApp ();
            }
      
            if (obj == btnNew) {

                  boolean b = openChildWindow ("Create New");
                  if (b == false) {
                        System.out.println("BUtton Clicked");
                        NewAccount newAcc = new NewAccount ();
                        desktop.add (newAcc);
                        newAcc.show ();
                  }

            }
            else if (obj == btnDep) {
                  
                  boolean b = openChildWindow ("Create New");
                  if (b == false) {
                        System.out.println("BUtton Clicked");
                        DisplayCity dc = new DisplayCity();
                        desktop.add (dc);
                        dc.show ();
                  }
            }
      }

      //Function Perform By LookAndFeel Menu.

      public void itemStateChanged (ItemEvent e) {

            for( int i = 0; i < radio.length; i++ )
                  if(radio[i].isSelected()) {
                        changeLookAndFeel (i);
                  }

      }      

      //Function For Closing the Program.

      private void quitApp () {

            try {
                  //Show a Confirmation Dialog.
                      int reply = JOptionPane.showConfirmDialog (this,
                              "Are you really want to exit\nFrom DslamSystem?",
                              "DslamSystem - Exit", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
                  //Check the User Selection.
                  if (reply == JOptionPane.YES_OPTION) {
                        setVisible (false);      //Hide the Frame.
                        dispose();                  //Free the System Resources.
                        System.out.println ("Thanks for Using DslamSystem\n");
                        System.exit (0);        //Close the Application.
                  }
                  else if (reply == JOptionPane.NO_OPTION) {
                        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                  }
            }

            catch (Exception e) {}

      }

      //Function for Changing the Program's Look.

      public void changeLookAndFeel (int val) {

            try {
                  UIManager.setLookAndFeel (looks[val].getClassName());
                  SwingUtilities.updateComponentTreeUI (this);
            }
            catch (Exception e) { }

      }

      //Loop Through All the Opened JInternalFrame to Perform the Task.

      private boolean openChildWindow (String title) {

            JInternalFrame[] childs = desktop.getAllFrames ();
            for (int i = 0; i < childs.length; i++) {
                  if (childs[i].getTitle().equalsIgnoreCase (title)) {
                        childs[i].show ();
                        return true;
                  }
            }
            return false;

      }
}
Add a MouseListener (to the button) that pops up the menu

http://javaalmanac.com/egs/javax.swing/Popup.html
Avatar of Zolf

ASKER


those site which shivaspk provided do not work.
Avatar of Zolf

ASKER


hi objects

i have got confussed,could you please tell me the steps to follow to acheive my goals.
try something like:

button.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent evt) {
            if (evt.isPopupTrigger()) {
                popupMenu.show(evt.getComponent(), evt.getX(), evt.getY());
            }
        }
        public void mouseReleased(MouseEvent evt) {
            if (evt.isPopupTrigger()) {
                popupMenu.show(evt.getComponent(), evt.getX(), evt.getY());
            }
        }
    });
Avatar of Zolf

ASKER

thanks objects.appreciate your help.now my code is like this.but i dont know how to insert popupmenu to button

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
      
public class FrameDemo //implements MouseListener
{
      JMenuBar menuBar;
      JMenu menu, submenu;
      JMenuItem menuItem;
      JButton btButton;
      JPopupMenu popupMenu;

      FrameDemo()
      {
            JFrame frame = new JFrame("FrameDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel emptyLabel = new JLabel("");
        emptyLabel.setPreferredSize(new Dimension(175, 100));
        frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
       
        popupMenu = new JPopupMenu();
       
            //      Create the menu bar.
                  menuBar = new JMenuBar();
            
            //      Build the first menu.
                  menu = new JMenu("A Menu");
            
            //  Add menu to  menu bar
                  menuBar.add(menu);
                  
                  btButton = new JButton("BUtton");
                  
//              Add menu to  menu bar
                  menuBar.add(btButton);
                  
//                  a group of JMenuItems

                  menuItem = new JMenuItem("Both text and icon",
                                           new ImageIcon("images/middle.gif"));
                  menuItem.setMnemonic(KeyEvent.VK_B);
                  menu.add(menuItem);
                  
                  frame.setJMenuBar(menuBar);

                  btButton.addMouseListener(new MouseAdapter() {
                    public void mousePressed(MouseEvent evt) {
                        if (evt.isPopupTrigger()) {
                            popupMenu.show(evt.getComponent(), evt.getX(), evt.getY());
                        }
                    }
                    public void mouseReleased(MouseEvent evt) {
                        if (evt.isPopupTrigger()) {
                            popupMenu.show(evt.getComponent(), evt.getX(), evt.getY());
                        }
                    }
                });
                  
              //Display the window.
              frame.pack();
              frame.setVisible(true);


      }

    public static void main(String[] args)
    {
        new FrameDemo();
    }
}
try this:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
     
public class FrameDemo //implements MouseListener
{
     JMenuBar menuBar;
     JMenu menu, submenu;
     JMenuItem menuItem;
     JButton btButton;
     JPopupMenu popupMenu;

     FrameDemo()
     {
          JFrame frame = new JFrame("FrameDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel emptyLabel = new JLabel("");
        emptyLabel.setPreferredSize(new Dimension(175, 100));
        frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
       
        popupMenu = new JPopupMenu();
       
          //     Create the menu bar.
               menuBar = new JMenuBar();
         
          //     Build the first menu.
               menu = new JMenu("A Menu");
         
          //  Add menu to  menu bar
               menuBar.add(menu);
               
               btButton = new JButton("BUtton");
               
//            Add menu to  menu bar
               menuBar.add(btButton);
               
//               a group of JMenuItems

               menuItem = new JMenuItem("Both text and icon",
                                        new ImageIcon("images/middle.gif"));
               menuItem.setMnemonic(KeyEvent.VK_B);
               menu.add(menuItem);
               
               popupMenu = new JPopupMenu();
               popupMenu.add(new JMenuItem("Test"));
               
               frame.setJMenuBar(menuBar);

               btButton.addMouseListener(new MouseAdapter() {
                  public void mousePressed(MouseEvent evt) {
                        System.out.println(evt);
                      //if (evt.isPopupTrigger()) {
                          popupMenu.show(evt.getComponent(), evt.getX(), evt.getY());
                      //}
                  }
                  public void mouseReleased(MouseEvent evt) {
                      //if (evt.isPopupTrigger()) {
                          popupMenu.show(evt.getComponent(), evt.getX(), evt.getY());
                      //}
                  }
              });
               
             //Display the window.
             frame.pack();
             frame.setVisible(true);


     }

    public static void main(String[] args)
    {
        new FrameDemo();
    }
}
Avatar of Zolf

ASKER


thanks mate.now is it possible to have a small black arrow next to the button which when clicked should open the menu.if you want i can open a new question for this.

cheers
zolf
you could probably use a seperate JLabel for that
Avatar of Zolf

ASKER


i want something like internet explorer back button.i have seen a java application having that.
Avatar of Zolf

ASKER


even google toolbar has got this feature.the first button on the google toobar
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial