JMenu.setDelay()

Has anyone used JMenu.setDelay() ?
The documentation says: "Sets the suggested delay before the menu's PopupMenu is popped up or down." and then goes on to talk about different UI implementations. We are using a derivitive of the metal look & feel on Windows 2000 and XP.
I was hoping that this control would also slow down the opening and closing of submenus. I do seem to get an open delay when I move the mouse down the parent menu (although I don't appear to be able to set the duration of that delay), but the submenu closes immediately my mouse passes beyond the current parent item.

I was hoping that this control would also slow down the opening and closing of submenus.When the documentation says "pop up or down" it means that when the menu is displayed it will normally "pop down", but if there is not enough room at the bottom of the frame then it will "pop up". It is not referring to the closing of the menu. Therefore the behaviour is working according to the documentation when I tested it.
I do seem to get an open delay when I move the mouse down the
parent menu (although I don't appear to be able to set the duration of that delay), The delay worked fine for me.
I tested using JDK1.4.2 on XP.

Similar Messages

  • Scroll down/up functionality in a jMenu?

    What i mean is a jMenu similar to that of internet explorer's
    Favorites menu. When you have a ton of favorites you get a little arrow
    pointing down or up depending on where you are in the menu. Is it possible to implement something similar in java with a jmenu? if so how?
    Ps thanks to all who helped with my previous JMenu question. I got it figured out :)

    Found this for you
    http://forum.java.sun.com/thread.jsp?forum=57&thread=310457&message=1250922#1250922

  • Dynamic jmenu bar

    i have a dynamic JMenu on a jframe. The menu is populated by looking up database entries and ptting them into the right place. This is done by a method 'menus()'.
    I also have an addingredients class which adds new ingredient entries into the database, problem is when it does this, the JMenu has to be repopulated. The following code shows the main frame
    // Recipe Creation GUI
    // Written by Michael Emett
    // Monday 15th Decemeber 2003
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JFrame.*;
    import java.sql.*;
    import java.util.*;
    public class TextAreaDemo extends JFrame     {
    private static JTextArea part1;
    private JButton Browse, Enter, Preview, Remove;
    public static JList printList, newList;
    private JCheckBox pic;
    private JLabel namePrompt, title1, title2, title3;
    private static JTextField nameInput;
    private JPanel jp, jp1, jp2, jp3, jp4, jp5;
    private Connection con;
    private Statement stmt;
    public static JMenu fileMenu;
    private static JMenuBar bar;
    // additions /////////////////////////////////////////////////////////////////////////
    //set up GUI
    public TextAreaDemo()     {
    super( "Recipe Entry Sheet" );
    // set up File menu and its menu items
    // Menu and button Initialization ////////////////////////////////////////////////////
    //myMouse = new MyMouseAdapter();
    //final JMenu
    fileMenu = new JMenu( "Ingredients");
             fileMenu.setMnemonic( 'I' );
    fileMenu.add(menus());
    bar = new JMenuBar();
    setJMenuBar( bar );
    JMenu file = new JMenu( "File");
    file.setMnemonic( 'F' );
        bar.add(file);
              JMenuItem Adder = new JMenuItem( "New Ingredient");
             Adder.setMnemonic( 'N' );
    JMenuItem Subber = new JMenuItem( "New subMenu");
             Subber.setMnemonic( 'S' );
             // set up About... menu item
             JMenuItem aboutItem = new JMenuItem( "About..." );
             aboutItem.setMnemonic( 'A' );
    namePrompt = new JLabel( "Recipe Name " );
    nameInput = new JTextField( 20 );
    title1 = new JLabel( "Selected ingredients" );
    title3 = new JLabel( "Please enter the Recipe Instructions" );
    title2 = new JLabel( "Enter The SubMenu Name " );
    pic = new JCheckBox("Add Picture", false);
    file.add( Adder );
         Adder.addActionListener(
              new ActionListener()     {
                    public void actionPerformed( ActionEvent event )
                        getList f = new getList();
    // Add Ingredient menu item //////////////////////////////////////////////////////////
    file.add( Subber );
         Subber.addActionListener(
              new ActionListener()     {
                    public void actionPerformed( ActionEvent event )
                        AddSubMenu f = new AddSubMenu();
    // About menu item ///////////////////////////////////////////////////////////////////
    file.add( aboutItem );
          aboutItem.addActionListener(
             new ActionListener() {  // anonymous inner class
                // display message dialog when user selects About...
                public void actionPerformed( ActionEvent event )
                   JOptionPane.showMessageDialog( TextAreaDemo.this,
                      "Developed by Michael Emett, 2004",
                      "About", JOptionPane.PLAIN_MESSAGE );
              }     // end anonymous inner class
         );  // end call to addActionListener
    // Exit menu item ////////////////////////////////////////////////////////////////////
         JMenuItem exitItem = new JMenuItem( "Exit" );
         exitItem.setMnemonic( 'x' );
         file.add( exitItem );
          exitItem.addActionListener(
             new ActionListener() {  // anonymous inner class
                // terminate application when user clicks exitItem
                public void actionPerformed( ActionEvent event )
                   System.exit( 0 );
             }  // end anonymous inner class
          ); // end call to addActionListener
    //create Button Enter
    Enter = new JButton("Enter");
    Enter.addActionListener(
              new ActionListener()     {
                              public void actionPerformed( ActionEvent event )
                        StringBuffer a = new StringBuffer();
                        StringBuffer b = new StringBuffer();
                        StringBuffer c = new StringBuffer();
                        for(int i= 0; i< victor.size(); i++){
                        b.append(victor.elementAt(i));
                        b.append("; ");
                        a.append(nameInput.getText());
                        c.append(part1.getText());
                        //System.out.println(a);
                        //System.out.println(b);
                        //System.out.println(c);
                        InsertRecipe f = new InsertRecipe(a,b,c);
                        //invalidate();
                //fileMenu.updateUI();
               // fileMenu.revalidate();
    //create Button Remove
    Remove = new JButton("Remove");
    //add Actionlistener
    Remove.addActionListener(
              new ActionListener()     {
                    public void actionPerformed( ActionEvent event )
    int[] arr;
    arr = printList.getSelectedIndices();
    int counter = 0;
         for (int i= 0; i< arr.length; i++){
              int n=arr;
              victor.remove(n-counter);
              counter++;
    printList.setListData(victor);
    //create Button Remove
    Browse = new JButton("Browse");
    //create Button Preview
    Preview = new JButton("Clear");
    Preview.addActionListener(
    new ActionListener() {  // anonymous inner class
    // display message dialog when user selects Preview...
    public void actionPerformed( ActionEvent event )
    int result = JOptionPane.showConfirmDialog
                             (null,      "Are you sure to want to clear this form", "Clear?",      JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
                             if(result == JOptionPane.YES_OPTION)
                             {TextAreaDemo.clear();
                                  //System.out.println("Recipe Entered");
              }//end of joptionpane
    printList = new JList();
    printList.setVisibleRowCount(9);
    printList.setFixedCellWidth(150);
    printList.setFixedCellHeight(15);
    printList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
    newList = new JList();
    newList.setVisibleRowCount(9);
    newList.setFixedCellWidth(150);
    newList.setFixedCellHeight(15);
    newList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION );
    // Initialise Text Areas //
    part1 = new JTextArea( 25, 50);
    part1.setFont(new Font("Courier", Font.BOLD, 12));
    part1.setLineWrap(true);
    part1.setWrapStyleWord(true);
    // JPanels for Layout //
    jp = new JPanel();
    jp1 = new JPanel();
    jp2 = new JPanel();
    jp3 = new JPanel();
    jp4 = new JPanel();
    jp5 = new JPanel();
    final Container c = getContentPane();
    GridBagLayout gbl = new GridBagLayout();
    GridBagConstraints gbc = new GridBagConstraints();
         c.setLayout(gbl);
         gbc.weightx = 0.1;
         gbc.weighty = 0.5;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.NORTHWEST;
    add(jp1, gbc, 0, 0, 1, 1);
    gbc.fill = GridBagConstraints.NONE;
    add(jp2, gbc, 0, 1, 1, 1);
    add(jp3, gbc, 1, 0, 2, 2);
    jp1.add(jp4, BorderLayout.CENTER);
    jp2.add(jp, BorderLayout.CENTER);
    bar.add( namePrompt );
    bar.add( nameInput);
    bar.add( fileMenu );
    jp4.setLayout(new BorderLayout());
    jp4.add(title1, BorderLayout.NORTH);
    jp4.add(new JScrollPane( printList), BorderLayout.CENTER);
    jp4.add(Remove, BorderLayout.SOUTH);
    jp.setLayout(new BorderLayout());
    jp.add(pic, BorderLayout.NORTH);
    jp.add(new JScrollPane (newList), BorderLayout.CENTER);
    jp.add(Browse, BorderLayout.SOUTH);
    jp3.setLayout(new BorderLayout());
    jp3.add (title3, BorderLayout.NORTH);
    jp3.add (new JScrollPane(part1), BorderLayout.CENTER);
    //c.addMouseListener(myMouse);
    gbc.anchor = GridBagConstraints.LAST_LINE_END;
    add(jp5, gbc, 2, 3, 1, 1);
    jp5.setLayout(new FlowLayout());
    jp5.add(Preview);
    jp5.add(Enter);
    setSize(770, 620);
         pack();
         setVisible(true);
         setResizable(false);
    private static Vector victor = new Vector();
    public static void printListset(String t) {
         victor.add(t);
    for(int i = 0; i<victor.size(); i++)
    printList.setListData(victor);
    public void add(Component ce, GridBagConstraints constraints, int x, int y, int w, int h) {
                   constraints.gridx = x;
                   constraints.gridy = y;
                   constraints.gridwidth = w;
                   constraints.gridheight = h;
                   getContentPane().add(ce, constraints);
    public static JMenu menus()     {
         // Map Created to Handle JMenuItem Addition //
              Map labelToMenu = new HashMap();
              Map labelToMenu2 = new HashMap();
              Map labelToMenu3 = new HashMap();
              String url = "jdbc:odbc:database";
              Connection con;
              Statement stmt;
                        try     {
                             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        catch(ClassNotFoundException e)     {
                        System.err.print("Class Not found");
                        String query = "select baseIngred.IngredientType, baseIngred.PrimaryKey FROM baseIngred";
                        String query2 = "select baseIngred.IngredientType, baseIngred.PrimaryKey,"
                        + "subMenu.menuNumber, subMenu.subMenu FROM baseIngred, "
                        + "subMenu WHERE baseIngred.PrimaryKey = subMenu.menuNumber ORDER BY submenu";
                                  String query3 = "select subMenu.subMenu, subMenu.PrimaryNumber,"
                                       + "Ingredient.Ingredient, Ingredient.MenuNumber FROM subMenu, Ingredient"
                        + " WHERE Ingredient.MenuNumber = subMenu.PrimaryNumber ORDER BY PrimaryNumber";
         String query4 = "select Ingredient.Ingredient, Ingredient.MenuNumber FROM Ingredient";
                             try     {
                                       con = DriverManager.getConnection(url, "myLogin", "myPassword");
                                       stmt = con.createStatement();
         // Initial Jmenu added ///////////////////////////////////////////////////////////////
                   ResultSet rs = stmt.executeQuery(query);
                   String[] arr = new String[100];
                   int[] num = new int[200];
                   int[] num2 = new int[200];
                   int counter = 0;
                   int counter2 = 0;
                   while     (rs.next())     {
                                  //String t is set to the value contained in ingredient type
                                  String t = rs.getString("IngredientType");
                                  //map labelToMenu has String t and a new JMenu with the menu
                                  //name contained in t stored in it
                                  labelToMenu.put(t, fileMenu.add(new JMenu(t)));
                                  //an array containing values of the priamry key is produced
                                  num[counter] = rs.getInt("PrimaryKey");
                                  //a counter is incremeted so that upon further
                                  //interations it is stored in a new array field
                                  counter++;
         // Second Jmenu added ////////////////////////////////////////////////////////////////
                   ResultSet rs2 = stmt.executeQuery(query2);
                   while     (rs2.next()) {
                                  //String first is set to the value contained in ingredient type
                                  String first = rs2.getString("IngredientType");
                                  //String second is set to the value contained in subMenu
                                  String second = rs2.getString("subMenu");
                                  //firstlevel looks up item t in the map, and creates a jmenu name as it.
                                  JMenu firstLevel = (JMenu)labelToMenu.get(first);
                                  //handles menu placement by comparing PrimaryKeys with MenuNumbers
                                  // f = rs2.getInt("menuNumber");
                                  num2[counter2] = rs2.getInt("menuNumber");
         for (int nm = 0; nm<num.length; nm++){
                   if (num[nm] == num2[counter2]
                                            //adds the second value to the jmenu with th name stored in t.
                                            labelToMenu2.put(second, (firstLevel.add(new JMenu (second))));
                                       }counter2++;
         // Third JMenu added /////////////////////////////////////////////////////////////////
         ResultSet rs3 = stmt.executeQuery(query3);
              while     (rs3.next()) {
                                  //String next is set to the value contained in subMenu
                                  String next = rs3.getString("subMenu");
                                  //String third is set to the value contained in ingredient
                                  String third = rs3.getString("Ingredient");
                                  JMenu secondLevel = (JMenu)labelToMenu2.get(next);
                                  int f2 = rs3.getInt("MenuNumber");
                                  //System.out.println(f2);
                                  int f3 = rs3.getInt("PrimaryNumber");
                   if (f3 == f2){
                             labelToMenu3.put(third, secondLevel.add(new JMenuItem(third)));
         // Add AtionListeners ////////////////////////////////////////////////////////////////
         ResultSet rs4 = stmt.executeQuery(query4);
              while     (rs4.next()) {
                   String third2 = rs4.getString("Ingredient");
         JMenuItem thirdLevel = (JMenuItem)labelToMenu3.get(third2);
         thirdLevel.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   JMenuItem source = (JMenuItem)(e.getSource());
                   String actionText = source.getText();
                   PopUp pop = new PopUp(actionText);
                        stmt.close();
                        con.close();
                             }catch(SQLException ex)     {
                        System.err.println(ex);
    return (fileMenu);
         //                                        End Of Connection                                             //
         // Add subMenu menu item /////////////////////////////////////////////////////////////
    public static void clear()     {
    nameInput.setText("");
    victor.removeAllElements();
    printList.setListData(victor);
    part1.setText("");
    public static void rebuild()     {
    fileMenu.removeAll();
    fileMenu.add(menus());
    bar.add( fileMenu );
    public static void main(String args[])     {
         TextAreaDemo t = new TextAreaDemo();
         t.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
    the code inside the method 'rebuild()' will work from inside the main JFrame body if assigned to a button (such as the example position denoted by HERE in the code), but that is undesirable as it requires the user to refresh manually every time they add a new ingredient. what i need is a method that can be called from another class/method/whatever.
    thankyou for any help you can offer, it is much appreciated

    The code you offered did not solve my problem. I have since entered the followinginto the actionlistener of a button on the JFrame,
    refreshMenu = new JButton("Refresh Menu");
    refreshMenu.addActionListener(
             new ActionListener() { 
                // display message dialog when user selects Preview...
                public void actionPerformed( ActionEvent event )
    fileMenu.removeAll();
    fileMenu.add(menus());
    bar.add( fileMenu );          
    );This does what i need, but i need these statements to be made from an external class, not a JButton,

  • Dynamic addition of  JMenuItem in JMenu

    I am trying to create a menu for my project. For that i have added the main menus and for each menu there will be menu item. But the problem is i will get the list of menu items for each menu , only at the runtime of my project. i.e. i wabt to add progrramatically add the menu items. Iam really confused with this. I will appriciate if any one help me on this.
    And also i want to know ..is that possible to get the mouse listener for menu.
    Thank in advance
    Regards,
    SAthish

    You can add and remove menu items from the jmenu dynamically, the only thing you will have to take care of is invoking validate() after each insertion/deletion (it's a bit buggy there). All you have to do is create the items on demand and add (remove) them via the add(JMenuItem) (remove(JMenuItem)) method.
    As for your second question, a JMenu is nothing but a JComponent, so you should be able to add a mouse listener like you would with any other component...

  • Event handling in JMenu in JPanel

    Hi,
    I'm writing a small register program GUI. I have a problem with ActionListener in JMenu. I wrote a JPanel which creates a JMenu and that works just fine. The problem is that id doesn't give any event signals. I have another class which impelemets ActionListener and it works fine with JButton (another panel for buttons), but not with JMenu.
    Below is the JPanel for JMenu and Application which implements the ActionListener. Do you see anything wrong? I really can't imagine why I cannot get the action signals. JPanel is defined in JFrame as it should be. Have you got any ideas?
    Regards,
    Marko
    class MenuPanel extends JPanel {
         protected JMenuBar menuBar;
         protected JMenu menu;
         protected JMenuItem loadRegister;
         protected JMenuItem saveRegister;
         protected JMenuItem information;
         protected JMenuItem quit;
         public MenuPanel(Application application) {
              menuBar = new JMenuBar();          
              menu = new JMenu("Tiedosto");     
              loadRegister = new JMenuItem("Lataa");
              loadRegister.addActionListener(application);
              saveRegister = new JMenuItem("Talleta");
              saveRegister.addActionListener(application);
              information = new JMenuItem("Tietoja");
              information.addActionListener(application);
              quit = new JMenuItem("Lopeta");                    quit.addActionListener(application);
              menu.add(loadRegister);
              menu.add(saveRegister);
              menu.addSeparator();
              menu.add(information);
              menu.add(quit);          
              menuBar.add(menu);
    class Application implements ActionListener {     
         // Define CardPanel
         private CardPanel cardPanel;
         // Define linked list for cards
         private CardList cardList = null;
         // Constructor. Initializes cardPanel and cardList
         public Application(CardPanel cardPanelRefrence) {
              cardPanel = cardPanelRefrence;
              cardList = new CardList();
         public void actionPerformed(ActionEvent action) {
              String actionPerformed = action.getActionCommand();
              if (actionPerformed.equals("Lataa")) {
                   load();          
              if (actionPerformed.equals("Talleta")) {
                   save();          
              if (actionPerformed.equals("Tietoja")) {
                   info();          
              if (actionPerformed.equals("Lopeta")) {
                   System.exit(0);
    // Continues with the methods...

    Well, I found the answer. Heh, quite easy one but it took a while before I found it..
    Just if you ever have similar problem. The problem was that in my JFrame I didn't create an object of class (Application) which implement s the ActionListener before using it as a reference in creating JPanel object. Quite confusing explanation, but here the code. This code was in my JFrame which was not included in this question.
    private Application application;
    private MenuPanel menuPanel;
    application = new Application(cardPanel, rightInfoPanel);
    menuPanel = new MenuPanel(application);
    These two were introduced other way round, so that variable "application" was null. What a problem in fact.. :)
    - Marko

  • Event Handling - In what layer/pane is a JMenu contained?

    In what layer is a JMenu contained?
    I ask this because I am trying to figure out what object gets the event first - the component with a keybinding of WHEN_IN_FOCUSED_WINDOW or my menu. I want my menu to clear itself for certain keystrokes and allow the event to be picked up by the component that is listening for it in the focused window.
    I know the FocusManager, focused component, gets to process the event first. Then to keylisteners of super(), Keybindings, and then menubar.
    I know the JFrame implements the RootPane interface. The RootPane contains a glassPane and a layeredPane. The layered pane puts the jmenubar(optional) and content pane in the JLayered panes frameContentLayer.
    The menu is added to the JMenuBar so is the menu in the JLayeredPane PopUpLayer or is it in the FrameContentLayer?
    If the menu is part of the menubar and the menu bar is the last to get notified...
    Would the JMenu receive an event only after a component in the content layer has processed it? Will the component in the content layer that is listening for a certain keypress in the focused window even get notified since the FocusManager has the event source as the JMenu?
    If anyone has any clarification on the JMenu and how events/panes/layers work with the JMenu I would greatly appreciate your help. I understand the other components I am just confused about the JMenu.

    JMenu is contained in default_layer
    DEFAULT_LAYER
    The standard layer, where most components go. This the bottommost layer.
    PALETTE_LAYER
    The palette layer sits over the default layer. Useful for floating toolbars and palettes, so they can be positioned above other components.
    MODAL_LAYER
    The layer used for modal dialogs. They will appear on top of any toolbars, palettes, or standard components in the container.
    POPUP_LAYER
    The popup layer displays above dialogs. That way, the popup windows associated with combo boxes, tooltips, and other help text will appear above the component, palette, or dialog that generated them.
    DRAG_LAYER
    When dragging a component, reassigning it to the drag layer ensures that it is positioned over every other component in the container. When finished dragging, it can be reassigned to its normal layer.

  • Problem with Alt , JMenu and Mnemonics

    I have built an application with a JMenuBar containing several JMenu's, the first of which is a File menu. All JMenus and JMenuItems have mnemonics associated with them. When I press the alt key the underlines show and focus appears to be given to the File menu (though it has not dropped down). If I then press a key, for example 'S', that is a mnemonic of the 'Save' jmenuitem in the File menu, the Save action is invoked. This should not occur because the menu has not opened yet.
    The behavior is what I'd expect had an accelerator (Alt+S) been defined for the Save menu item. But I have not defined any accelerators.
    Why does this happen and more importantly, is there a work around?

    Except for the 1st line in jbinit() it's all pretty standard stuff. Here's a snippet of the code:
    public class MainFrame extends JFrame implements ChangeListener {
    JMenuBar jMenuBar1 = new JMenuBar();
    JMenu jMenuFile = new JMenu();
    JMenuItem jMenuFileNew = new JMenuItem();
    JMenuItem jMenuFileSave = new JMenuItem();
    JMenu m_editMenu = new JMenu();
    JMenuItem m_editCutMenuItem = new JMenuItem();
    JMenuItem m_editCopyMenuItem = new JMenuItem();
    JMenuItem m_editPasteMenuItem = new JMenuItem();
    public MainFrame() {
    jbInit();
    //Component initialization
    private void jbInit() {
    getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
    KeyStroke.getKeyStroke(KeyEvent.VK_ALT, Event.ALT_MASK, false), "repaint");
    // file menu
    jMenuFile.setText("File");
    jMenuFile.setMnemonic(KeyEvent.VK_F);
    jMenuFileNew.setText("New...");
    jMenuFileNew.setMnemonic(KeyEvent.VK_N);
    jMenuFileNew.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jMenuFileNewSpecial_actionPerformed(e);
    jMenuFileSave.setText("Save");
    jMenuFileSave.setMnemonic(KeyEvent.VK_S);
    jMenuFileSave.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jMenuFileSaveSpecial_actionPerformed(e);
    jMenuFile.add(jMenuFileNew);
    jMenuFile.add(jMenuFileSave);
    // edit menu
    m_editMenu.setText("Edit");
    m_editMenu.setMnemonic(KeyEvent.VK_E);
    m_editCutMenuItem.setText("Cut");
    m_editCutMenuItem.setMnemonic(KeyEvent.VK_T);
    m_editCutMenuItem.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    editCutMenuItem_actionPerformed(e);
    m_editCopyMenuItem.setText("Copy");
    m_editCopyMenuItem.setMnemonic(KeyEvent.VK_C);
    m_editPasteMenuItem.setText("Paste");
    m_editPasteMenuItem.setMnemonic(KeyEvent.VK_P);
    m_editMenu.add(m_editCutMenuItem);
    m_editMenu.add(m_editCopyMenuItem);
    m_editMenu.add(m_editPasteMenuItem);
    jMenuBar1.add(jMenuFile);
    jMenuBar1.add(m_editMenu);
    this.setJMenuBar(jMenuBar1);
    etc...
    Pressing Alt+S invokes the action listener for the jMenuFileSave menu item. It should do nothing since there is no top level menu with a mnemonic of 'S'.

  • Adding JMenu directly to a JPanel

    I am trying to add a JMenu directly to a JPanel, but it isn't functioning properly. It shows up, and looks the way I expect (with an arrow, like a sub-menu), but it doesn't display its popup menu when clicked. If I add the menu to a JMenuBar, and add that to the panel, it works, but the popup drops down below the button instead of to the right, and the arrow disappears. JMenuBar appears to be adding its own actions to every menu that it contains. JMenu is a descendant of AbstractButton, so I figured it would behave like one, but no luck.
    Any help would be appreciated. By the way, I have thought of using a JButton and a JPopupMenu together, but that is not a very elegant solution. I am looking for a way to make the JMenu behave as if it were in a JMenuBar.

    Hello Vijesh
    See the code below and tell me whether it is useful ?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class SwingA implements ActionListener
    JPopupMenu pop;
    JFrame frame;
    JPanel panel;
    JButton cmdPop;
         public static void main(String[] args)
         SwingA A=new SwingA();
         SwingA()
                   frame=new JFrame("PopUp");
                   frame.setSize(600,480);
                   frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
                   pop=new JPopupMenu();
                   cmdPop=new JButton("Click");
                   cmdPop.addActionListener(this);
    JMenuItem item = new JMenuItem("First");
    JMenuItem item1 = new JMenuItem("Second");
    pop.add(item);
    pop.add(item1);
                   panel=new JPanel();
                   panel.add(cmdPop);
                   frame.getContentPane().add(panel);
                   frame.setVisible(true);
         public void actionPerformed(ActionEvent source)
    pop.show(cmdPop, cmdPop.getWidth(), 0);
    kanad

  • How to activate JMenu from other frame using accelerator key

    Hi.
    I'm developing an application for my final year project.
    i set up my application to have multiple frame open at the same time (like sunone studio in SDI mode). only one JFrame contains the JMenuBar.
    i can activate this menu bar using the accelerator key when the containing JFrame has focus. however, i donot know how to make the Menu activate when the accelerator key is pressed on other frame. press help, thanks in advance.

    does any one have some idea.
    the solution i found seem not suit my need.
    i want to be able to pull down (and get the focus transfered to) the jmenu in menubar of another frame using the menu's mnemonics. using InputMap does not seem to fit since i need to the menmonic of menu is not in the input map.

  • JTable in a JMenu

    It is posibble to add a jtable in jmenu ??

    This is what i;m trying to get : http://kynamar.dublu.ro/java/emoticoane.html
    Follow the link please.
    I have a jtable with all the icons but i don't know how to add to jmenu!
    In that thread the jmenu have 2 columns,not 10 for example!
    This is my jtable of icons
    import java.util.Enumeration;
    import java.util.Vector;
    import javax.swing.ImageIcon;
    import javax.swing.table.AbstractTableModel;
    * @author marian.radu
    public class ModelTabelSmyleys extends AbstractTableModel {
        protected Vector<ImageIcon> data;
        protected Vector<String> columnNames ;
        /** Creates a new instance of ModelTabelSmyleys */
        public ModelTabelSmyleys() {
            data=new Vector<ImageIcon>();
            columnNames=new Vector<String>();
            columnNames.addElement("");
            columnNames.addElement("");
            columnNames.addElement("");
            columnNames.addElement("");
            //columnNames.addElement("");
            //columnNames.addElement("");
            ObiectSmyleys smyleys=new ObiectSmyleys();
            smyleys.initializare();
            Enumeration enumeratie=smyleys.getContinut().keys();
                                while(enumeratie.hasMoreElements())
                                    String urmatorul=enumeratie.nextElement().toString();
                                           data.addElement(smyleys.getContinut().get(urmatorul));
        public int getRowCount() {
        return data.size() / getColumnCount();
      public int getColumnCount(){
        return columnNames.size();
      public String getColumnName(int columnIndex) {
        String colName = "";
        if (columnIndex <= getColumnCount())
           colName = columnNames.elementAt(columnIndex);
        return colName;
      public Class getColumnClass(int columnIndex){
        return ImageIcon.class;
      public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
      public void removeRow(int rowIndex)
          for(int i = 0;i < getColumnCount();i++)
          data.removeElementAt((rowIndex * getColumnCount()));
      public Object getValueAt(int rowIndex, int columnIndex) {
        return data.elementAt
            ( (rowIndex * getColumnCount()) + columnIndex);
      public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        data.setElementAt((ImageIcon)aValue,(rowIndex * getColumnCount()) + columnIndex);
    import java.io.File;
    import java.io.IOException;
    import java.util.Hashtable;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    * @author marian.radu
    public class ObiectSmyleys {
        private Hashtable<String,ImageIcon> continut=new Hashtable<String,ImageIcon>();
        /** Creates a new instance of ObiectSmyleys */
        protected String calea_dir_cur()
                String cale=""; //initializare cale nula
                try
                    File f=new File(".");
                    cale=f.getCanonicalPath();
                }catch(IOException err){}
                return cale;
        public Hashtable<String,ImageIcon> getContinut()
            return continut;
        public void addSmyleys(String toolTip,String nume_fisier)
            //JLabel label=new JLabel();
            ImageIcon imagine=new ImageIcon(calea_dir_cur()+"\\smiley\\"+nume_fisier);
            //label.setIcon(imagine);
            //label.setToolTipText(toolTip);
            continut.put(toolTip,imagine);
        public ObiectSmyleys() {
        public void initializare()
           addSmyleys(":-)","1.png");
           addSmyleys(":-(","2.png");
           addSmyleys(";-)","3.png");
           addSmyleys(":-D","4.png");
           addSmyleys(":-P","10.png");
           addSmyleys(":-*","11.png");
           addSmyleys(":-X","8.png");
           addSmyleys(":-))","20.png");
        public static void main(String[] args)
            ObiectSmyleys smyle=new ObiectSmyleys();
            System.out.println(smyle.getContinut().size());
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.text.TabExpander;
    * @version 1.0 06/19/99
    public class AnimatedTableIconExample extends JFrame {
      public AnimatedTableIconExample(){
        super( "AnimatedIconTable Example" );
        final JTable table = new JTable(new ModelTabelSmyleys());
        table.addMouseListener(new MouseAdapter()
        public void mouseClicked(MouseEvent e)
            if (e.getClickCount()==1)
                System.out.println("De 2 ori");
                System.out.println(table.getIntercellSpacing());
               System.out.println(table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()));
        table.setAutoResizeMode(table.AUTO_RESIZE_OFF);
        for(int i=0;i<table.getModel().getColumnCount();i++)
            table.getColumnModel ().getColumn(i).setMaxWidth(18);
        table.setRowHeight(18);
        table.setColumnSelectionAllowed(false);
        table.setRowSelectionAllowed(false);
        table.setCellSelectionEnabled(true);
        table.setIntercellSpacing(new Dimension(0,0));
        //setImageObserver(table);
        JScrollPane pane = new JScrollPane(table);
        getContentPane().add(pane);
        table.repaint();
      private void setImageObserver(JTable table) {
        TableModel model = table.getModel();
        int colCount = model.getColumnCount ();
        int rowCount = model.getRowCount();
        for (int col=0;col<colCount;col++) {
          if (ImageIcon.class == model.getColumnClass(col)) {
            for (int row=0;row<rowCount;row++) {
              ImageIcon icon = (ImageIcon)model.getValueAt(row,col);
              if (icon != null) {
                icon.setImageObserver(new CellImageObserver(table, row, col));
      class CellImageObserver implements ImageObserver {
        JTable table;
        int row;
        int col;
        CellImageObserver(JTable table,int row, int col) {
          this.table = table;
          this.row   = row;
          this.col   = col;
        public boolean imageUpdate(Image img, int flags,
                       int x, int y, int w, int h) {
          if ((flags & (FRAMEBITS|ALLBITS)) != 0) {
            Rectangle rect = table.getCellRect(row,col,false);
            table.repaint(rect);
          return (flags & (ALLBITS|ABORT)) == 0;
      public static void main(String[] args) {
        AnimatedTableIconExample frame = new AnimatedTableIconExample();
        frame.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
        frame.setSize( 300, 150 );
        frame.setVisible(true);
    }

  • JMenu with text and icon

    Is it possible to create a JMenu with text and an icon where only the icon brings up the menu and the text behaves like a JMenuItem? How would you do this. Right now I have a JMenuItem next to a JMenu where the JMenu only has an icon. The problem with this is it is seemingly impossible to get them as close together as I would like. Any suggestions for solving the spacing issue would be equally helpfull. Thanks.

    From your previous thread you are aware that JMenu and JMenuItem both extend AbstractButton. So, you should be able to play with the borders and margins:
    setBorder(null);
    setMargin( new Insets(0, 0, 0, 0) );

  • How to set JMenu/JMenuItem.accelerator property in Inspector

    How do you set an accelerator key through the accelerator
    property in the inspector for a JMenu or JMenuItem object? The
    list box contains one item, "<none>". Does one have to create
    some special keyboard shotcut objects that then will be added to
    the list?
    Where can one find documentation for the Swing classes, as far
    as I can see it's not included?
    Thanks.
    Finn Ellebaek Nielsen
    ChangeGroup ApS
    null

    I know how to do it in the code but it must be possible to do it
    from the Inspector since the property is listed there?
    Thanks.
    Finn
    JDeveloper Team (guest) wrote:
    : Finn,
    : I would check the Swing documentation available from the
    Javasoft
    : website for more information on these controls.
    : -L
    : Finn Ellebaek Nielsen (guest) wrote:
    : : How do you set an accelerator key through the accelerator
    : : property in the inspector for a JMenu or JMenuItem object?
    The
    : : list box contains one item, "<none>". Does one have to
    create
    : : some special keyboard shotcut objects that then will be
    added
    : to
    : : the list?
    : : Where can one find documentation for the Swing classes, as
    far
    : : as I can see it's not included?
    : : Thanks.
    : : Finn Ellebaek Nielsen
    : : ChangeGroup ApS
    null

  • JMenu's

    I have a components in my program that are used by both a JMenu and a JPopupMenu. The problem is that if I tell the my application to add the components to the JMenu and then to the JPopupMenu it won't appear in the JMenu, As if it wasn't added. But it appears in the JMenu! What went wrong?

    I suspect this is the same as most Swing things...
    If you try to add the same JPanel into West and East of a BorderLayout the JPanel will only appear in the last place you added it.
    I suspect you need to duplicate the JMenuItems and add 1 set to the JMenu & one the JPopupMenu... you should be able to attach the same listener to the items though to save some code duplication.

  • Problems with JMenu

    Hi,
    i have a problem with the JMenu in a project.
    The JMenu starts with a normal behaviour.
    After a time an error occurs:
    One JMenuitem is selected, and every move in the JMenu changes the selection only for a short time.
    Then the selection jumps back to the former
    selection.
    Anyone who knows this problem?
    Thanks
    Guido

    I now know when the trouble starts. When i start a DragnDrop action and then moves above the JMenu the odd behaviour starts. With the same trick this behaviour ends.
    I'm now searching for a way to avoid this trouble.
    The JMenu is not a Droptarget.
    Any suggestions?
    Guido

  • JMenu/JFrame issue

    Ok, I can't figure out how to make an option in a menu popup a new JFrame instead of displaying some stupid text in a text box.
    menuItem2 = new JMenuItem("Inventory");
              menuItem2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.ALT_MASK));
              menuItem2.getAccessibleContext().setAccessibleDescription("This does nothing for now");
              menu.add(menuItem2);That's just a tiny part...I need it to open the JFrame Inven if anybody knows how to do that.

    (post #2 - another disappeared into the ether)
    is this what you're trying to do?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      public Testing()
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocation(400,200);
        setSize(300,200);
        JMenu menu = new JMenu("Window");
        JMenuItem menuItem1 = new JMenuItem("Employees");
        JMenuItem menuItem2 = new JMenuItem("Inventory");
        menu.add(menuItem1);
        menu.add(menuItem2);
        JMenuBar menuBar = new JMenuBar();
        menuBar.add(menu);
        setJMenuBar(menuBar);
        getContentPane().add(new JTextArea(5,20));
        menuItem1.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            JFrame frame = new JFrame("Employee Frame");
            frame.setSize(200,100);
            frame.setLocation(100,500);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setVisible(true);}});
        menuItem2.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            JFrame frame = new JFrame("Inventory Frame");
            frame.setSize(200,100);
            frame.setLocation(500,500);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setVisible(true);}});
      public static void main(String[] args){new Testing().setVisible(true);}
    }

Maybe you are looking for

  • Is there any way to print to cheque via Tcode FCHN?

    Hi All, From Tcode FCHN, once the report is generated, i would like to print the "name of payee" ,  "Amount paid (FC)" and "Pmnt Date" to a cheque. For the "amount paid (FC)" which is in digits form, i would also need to convert into text/words. and

  • Standard 9, missing EDIT PDF PORTFOLIO side bar after recent update

    I can't find the place to enable the view of the "EDIT PDF PORTFOLIO" sidebar. I've always had it, but Acrobat updated recently, and it's gone. 

  • Lost contacts in sync modified where are they now?....

    hi all, i went to sync my phone and was promted that itunes would modify a certain number of my contacts and i accidently hit yes. when i went to my phone several of my contacts are not there. can someone tell me how to reverse that process and how t

  • Importing GoPro 4 footage

    I'm a bit confused about how to best use the GoPro 4 footage in FCP. Looking online, I've found a lot of posts about converting, mostly selling video conversion software. GoPro has GoPro Studio which seems to be the way to go, but it creates a Cinefo

  • Install of PC Suite causes restart of Windows

    I have windows 2000 sp4 and am installing the latest version of the PC Suite MSI and every time I try runing the installer it gets to the page where the installation begins, waits about two or three seconds, the screen hoes black and windows restarts