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
zolfAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

objectsCommented:
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)
0
zolfAuthor Commented:

hi objects,

could you please give me some java example of doing this.
0
objectsCommented:
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
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

zolfAuthor Commented:

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
0
Siva Prasanna KumarPrincipal Solutions ArchitectCommented:
0
zolfAuthor Commented:

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);
        }
    };
0
zolfAuthor Commented:

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;

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

http://javaalmanac.com/egs/javax.swing/Popup.html
0
zolfAuthor Commented:

those site which shivaspk provided do not work.
0
zolfAuthor Commented:

hi objects

i have got confussed,could you please tell me the steps to follow to acheive my goals.
0
objectsCommented:
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());
            }
        }
    });
0
zolfAuthor Commented:
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();
    }
}
0
objectsCommented:
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();
    }
}
0
zolfAuthor Commented:

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
0
objectsCommented:
you could probably use a seperate JLabel for that
0
zolfAuthor Commented:

i want something like internet explorer back button.i have seen a java application having that.
0
zolfAuthor Commented:

even google toolbar has got this feature.the first button on the google toobar
0
objectsCommented:
Swing doesn't supply anything for doing that sort of thing out of the box.
I'd probably implement it using something like two buttons wrapped in a panel.
another alternative would be writing your own L&F but there'd be a bot of work there.
or hit google in search of an existing impementation.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.