[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

menubar with picture

Posted on 2006-04-10
19
Medium Priority
?
446 Views
Last Modified: 2008-02-01

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
0
Comment
Question by:zolf
  • 10
  • 8
19 Comments
 
LVL 92

Expert Comment

by:objects
ID: 16415472
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
 

Author Comment

by:zolf
ID: 16415555

hi objects,

could you please give me some java example of doing this.
0
 
LVL 92

Expert Comment

by:objects
ID: 16415572
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:zolf
ID: 16415714

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
 

Author Comment

by:zolf
ID: 16415984

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
 

Author Comment

by:zolf
ID: 16416141

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
 
LVL 92

Expert Comment

by:objects
ID: 16422855
Add a MouseListener (to the button) that pops up the menu

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

Author Comment

by:zolf
ID: 16424295

those site which shivaspk provided do not work.
0
 

Author Comment

by:zolf
ID: 16424305

hi objects

i have got confussed,could you please tell me the steps to follow to acheive my goals.
0
 
LVL 92

Expert Comment

by:objects
ID: 16424320
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
 

Author Comment

by:zolf
ID: 16424635
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
 
LVL 92

Expert Comment

by:objects
ID: 16424853
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
 

Author Comment

by:zolf
ID: 16424965

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
 
LVL 92

Expert Comment

by:objects
ID: 16424986
you could probably use a seperate JLabel for that
0
 

Author Comment

by:zolf
ID: 16425038

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

Author Comment

by:zolf
ID: 16425053

even google toolbar has got this feature.the first button on the google toobar
0
 
LVL 92

Accepted Solution

by:
objects earned 2000 total points
ID: 16425056
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses
Course of the Month20 days, 6 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question