Accelerators in JPopupMenu

it is possible to add key-accelerators in the menuitems, these items get printed inside the menuitem (e.g. "Alt+2"). they work in a menubar, but they don't work in a popupmenu. why? i need accelerators from a popupmenu!

this seems not to be as simple, since JPopupMenu doesn't implement KeyListener interface. i tried to make a derived class (from JPopupMenu), implementing this interface and calling processKeyEvent(), but this seems not working... so HOW IS IT POSSIBLE TO USE ACCELERATORS WITH JPOPUPMENU ?

Similar Messages

  • Problem with JPopupMenu and JTree

    Hi,
    Is there any way to have different JPopupMenu for every node.
    When I right click on the treenode there is popup menu have a "*JCheckBoxMenuItem*". By default the value of that checkbox is false. Now when i try to right click on a particular node and select the checkbox the selected value gets applied to rest of all nodes also.
    How can i just set the value of the checkbox to one perticular node.
    my code is
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress=new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ie) {
                            if(compress.getState()){
                                 compress.setState(true);
                                    System.out.println("compress clicked");
                            else{
                                 compress.setState(false);
                                    System.out.println("uncompress");
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if(path!=null && path==tree.getAnchorSelectionPath()) {
            super.show(c, x, y);
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }Please help me as soon as possible.
    Thanks.
    Edited by: Kavita_S on Apr 23, 2009 11:49 PM

    Hi,
    Do you know this link?
    [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html]
    Please help me as soon as possible.Sorry that I'm not good at English, I don't understand what you mean.
    Anyway, here's a quick example:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest3 {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress = new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ie) {
              if (compress.getState()) {
                System.out.println("compress clicked");
                setSelectedPath(path, true);
              } else {
                System.out.println("uncompress");
                setSelectedPath(path, false);
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if (path!=null && path==tree.getAnchorSelectionPath()) {
            compress.setState(isSelectedPath(path));
            super.show(c, x, y);
      class MyData {
        public boolean flag;
        public String name;
        public MyData(String name, boolean flag) {
          this.name = name;
          this.flag = flag;
        @Override public String toString() {
          return name;
      //private Set<TreePath> selectedPath = new HashSet<TreePath>();
      private void setSelectedPath(TreePath p, boolean flag) {
        //if (flag) selectedPath.add(p);
        //else    selectedPath.remove(p);
        DefaultMutableTreeNode node =
              (DefaultMutableTreeNode)p.getLastPathComponent();
        Object o = node.getUserObject();
        if (o instanceof MyData) {
          ((MyData)o).flag = flag;
        } else {
          node.setUserObject(new MyData(o.toString(), flag));
      private boolean isSelectedPath(TreePath p) {
        //return selectedPath.contains(p);
        Object o =
              ((DefaultMutableTreeNode)p.getLastPathComponent()).getUserObject();
        return (o instanceof MyData)?((MyData)o).flag:false;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest3().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

  • Problem with  JTree and JPopupMenu

    Hi,
    I'm using a JPopupMenu with a JPanel in it. In the panel
    I want to have a JTree. I can build the tree without
    problems but when I try to "go down" in the tree it
    vanishes. This happens only the first time that I
    access a node. When I initialize the menu a second
    time the node I just pressed works fine.
    What is the problem????
    Here is a sample of my code.
    popUpMenu = new JPopupMenu();
    thePanel = new JPanel();
    thePanel .setLayout(new GridBagLayout());
    popUpMenu .add(thePanel );
    DefaultMutableTreeNode top = new DefaultMutableTreeNode("The top");
    DefaultMutableTreeNode secondNode = null;
    DefaultMutableTreeNode firstNode = null;
    firstNode = new DefaultMutableTreeNode("One node");
    top.add(firstNode);
    secondNode= new DefaultMutableTreeNode("One node");
    firstNode.add(secondNode);
    buildConstraints(gbc, 1, 0, 1, 5, 5, 5, 5, 2, 1); //My contraintsmethod
    JTree tree = new JTree(top);
    thePanel .add(tree, gbc);

    Mate, why are you putting a JPanel in a JPopupMenu? I'd be interested to look at a screenshot of this.
    Mitch

  • Problem with InputVerifier and JPopupMenu

    Hello, I have a problem related to the usage of InputVerifier and JPopupMenu.
    Consider the following scenario:
    - A frame composed of two components: a JTextField and a JComboBox
    - An InputVerifier that was set in the JComboBox (and in its associated JTextComponent)
    - A JPopupMenu which is enabled by a right mouse click over the components of the frame.
    The verify() method of the InputVerifier class is executed every time the focus is on the JComboBox and is requested by other component.
    Suppose that the focus is on the JComboBox, and a right mouse click is executed over this components. In summary, we have:
    1) The method verify() of the InputVerifier associated to the JComboBox is executed
    2) The focus changes from the JTextComponent (associated to the JComboBox) to the JRootPane (associated to the JTextComponent (that is associated to the JPopupMenu)).
    Now suppose that, the user clicks in the JTextField component (note that the JPopupMenu is visible and has the focus). What happens is that the focus goes from the JRootPane -> JTextComponent (associated to the JComboBox) -> JTextField.
    Despite the focus flow through the JTextComponent, the Swing plattaform, when executing the runInputVerifier() in the JComponent context, get the JRootPane component as the focusOwner instead of the JTextComponent.
    In this way, the Swing platform tries to invoke the InputVerify of the JRootPane (that is set with "null"), and the JComboBox InputVerifier is not executed as expected.
    It works as if the focus is flowing from the JRootPane directly to the JTextField.
    However, if the user clicks on the JComboBox before clicking in the JTextField, the Swing platform executes the correct InputVerifier, i.e., the one associated to the JComboBox (actually, the one associated to the JTextComponent).
    Any thoughts to solve this problem?
    Thanks

    A plus information, I am using jdk1.5.0_22.

  • Focus problem when JPopupMenu is shown

    I have compiled and ran the following 'JPopupTest.java' in JDK 1.4.1 on Windows. Kindly conduct the two tests as given below
    First Test :
    ============
    The class shows an editable JComboBox and a JButton when visible. Now click the down-arrow button of the JComboBox and make the drop-down popup visible. Then click on the "OK" button while the popup is visible. The popup gets hidden and a dialog is displayed as it should be.
    Second Test :
    =============
    Run the appilcation again. This time type something in the editable textfield of the JComboBox. A custom JPopupMenu with the text "Hello World" would be visible. Then click on the "OK" button while the popup is visible. The expected dialog is not shown. The custom JPopupMenu gets hidden. Now click on "OK" button again. The dialog is visible now.
    My Desire :
    ===========
    When I click on the "OK" button in the "Second Test" the JPopupMenu should get hidden and the dialog gets displayed (as it happens for the "First Test") in one click.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.plaf.basic.*;
    import java.util.*;
    public class JPopupTest extends JPanel implements DocumentListener, ActionListener
         JButton button;
         Vector vec;
         JComboBox jcombobox;
         JPopupMenu jpopupmenu;
         BasicComboBoxEditor _bcbe;
         JTextField jtextfield;
         public JPopupTest()
            vec = new Vector();
               vec.addElement("One");
            vec.addElement("Two");
            vec.addElement("Three");
            vec.addElement("Four");
            vec.addElement("Five");
            vec.addElement("Six");
            vec.addElement("Seven");
            vec.addElement("Eight");
            vec.addElement("Nine");
            vec.addElement("Ten");
            jcombobox = new JComboBox(vec);
            jcombobox.setEditable(true);
            _bcbe = ((BasicComboBoxEditor) jcombobox.getEditor());
            jtextfield = ((JTextField) _bcbe.getEditorComponent());
            jtextfield.getDocument().addDocumentListener(this);
            add(jcombobox);
            button = new JButton("OK");
            button.addActionListener(this);
            add(button);
            jpopupmenu = new JPopupMenu();
            jpopupmenu.add("Hello World");
         public void insertUpdate(DocumentEvent e)  {changedUpdate(e);}
         public void removeUpdate(DocumentEvent e)  {changedUpdate(e);}
            public void changedUpdate(DocumentEvent e)
            if(!jpopupmenu.isVisible())
            jpopupmenu.show(jcombobox, 0, jcombobox.getHeight());
            jtextfield.requestFocus();
         public void actionPerformed(ActionEvent e)
            JOptionPane.showMessageDialog(this, "OK button was pressed");
         public static void main(String[] args)
            JPopupTest test = new JPopupTest();
            JFrame jframe = new JFrame();
            jframe.getContentPane().add(test);
            jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            jframe.setSize(200,100);
            jframe.setVisible(true);

    See the code below with auto complete of text. When button is pressed, still TF gets focus after JOptionPane dialog is closed.
    -Pratap
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.plaf.basic.*;
    public class JPopupTest extends JPanel implements ActionListener {
         JButton button;
         Vector vec;
         JComboBox jcombobox;
         BasicComboBoxEditor _bcbe;
         JTextField jtextfield;
         MyComboUI comboUi = new MyComboUI();
         public JPopupTest() {
              vec = new Vector();
              vec.addElement("One");
              vec.addElement("Two");
              vec.addElement("Three");
              vec.addElement("Four");
              vec.addElement("Five");
              vec.addElement("Six");
              vec.addElement("Seven");
              vec.addElement("Eight");
              vec.addElement("Nine");
              vec.addElement("Ten");
              jcombobox = new JComboBox(vec);
              jcombobox.setEditable(true);
              jcombobox.setUI(comboUi);
              add(jcombobox);
              button = new JButton("OK");
              button.addActionListener(this);
              add(button);
              _bcbe = ((BasicComboBoxEditor) jcombobox.getEditor());
              jtextfield = ((JTextField) _bcbe.getEditorComponent());
              jtextfield.addCaretListener(new CaretListener() {
                        public void caretUpdate(CaretEvent e) {
                             if (!jcombobox.isPopupVisible() && jtextfield.isShowing() &&
                                       jtextfield.hasFocus()) {
                                  jcombobox.showPopup();
                             String text = jtextfield.getText().toLowerCase();
                             int index = -1;
                             for (int i = 0; i < jcombobox.getItemCount(); i++) {
                                  String item = ((String) jcombobox.getItemAt(i)).toLowerCase();
                                  if (item.startsWith(text)) {
                                       index = i;
                                       break;
                             if (index != -1) {
                                  comboUi.getList().setSelectedIndex(index);
                             } else {
                                  comboUi.getList().clearSelection();
                   jtextfield.addKeyListener(new KeyAdapter() {
                        public void keyPressed(KeyEvent e) {
                             if (e.getKeyCode() == e.VK_ENTER) {
                                  Object value = comboUi.getList().getSelectedValue();
                                  jcombobox.setSelectedItem(value);
                                  jcombobox.hidePopup();
         public void actionPerformed(ActionEvent e) {
              JOptionPane.showMessageDialog(this,"OK button was pressed");
              jtextfield.requestFocus();
         public static void main(String[] args) {
              JPopupTest test = new JPopupTest();
              JFrame jframe = new JFrame();
              jframe.getContentPane().add(test);
              jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jframe.setSize(200,100);
              jframe.setVisible(true);
         public class MyComboUI extends BasicComboBoxUI {
              public JList getList() {
                   return listBox;

  • How can I distinguish a JMenuItem , JPopupMenu and TopLevelMenu?

    I used the following methods to get the component who (a menu)gains the focus:
    JComponent com = JFrmame.getFocusOwner();
    or
    MenuSelectionManager menuMgr = MenuSelectionManager.defaultManager();
    MenuElement[] menuPath = menuMgr.getSelectedPath();
    if(menuPath != 0) {
    JComponent comp = Array.get(menuPath, menuPath.length-1); // this is the item with the focus
    then I need to use getAction() to get the menuItem's action. But how can I filter JMenuItem and JPopUpMenu from TopLevelMenu (JMenuBar item) ?
    Thanks!

    The instanceof may provide the simplest solution, since JPopupMenu, JMenuBar and JMenuItem don't have any kind of ancestor relationship with each other.if (comp instanceof JPopupMenu) {
        // Popup
    } else if (comp instanceof JMenuItem) {
        // Item
    } else if (comp instanceof JMenuBar) {
        // Bar
    } else ...?Hope this helps,
    -Troy

  • Change the color of seperator in JPopupMenu

    hi all,
    i want to change the color of the seperator in JPopupMenu?
    how to do this?
    pls help...
    -Soni

    try this :
    UIManager.put("Separator.foreground",Color.red);
    SwingUtilities.updateComponentTreeUI(this);

  • JPopupMenu with JInternalFrame, popup menu doesn't work

    hi, i have this problem, as shown in the sample code at the end of this post.. basically, i have a table, and i added a JPopupMenu onto the table.. the popup menu works well when running the table class, though, when i call the table class in a JInternalFrame environment, the popup menu won't work.. anyone know why?
    ///Basic sample table code, when run this alone, the popup menu will work
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TableBasic extends JPanel
         private JTable table;
         public TableBasic()
              String[] columnNames = { "Date", "String", "Integer", "Boolean" };
              Object[][] data =
                   {  { new Date(), "A", new Integer(1), Boolean.TRUE },
                        { new Date(), "B", new Integer(2), Boolean.FALSE },
                        { new Date(), "C", new Integer(9), Boolean.TRUE },
                        { new Date(), "D", new Integer(4), Boolean.FALSE}
              table = new JTable(data, columnNames)
                   //Returning the Class of each column will allow different
                   //renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane(table);
              add(scrollPane);
         public void createPopupMenu()
              JMenuItem menuItem;
              //Create the popup menu.
              JPopupMenu 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);
              //Add listener to the text area so the popup menu can come up.
              MouseListener popupListener = new PopupListener(popup);
              table.addMouseListener(popupListener);
         public static void main(String[] args)
              JFrame frame = new JFrame();
              TableBasic table = new TableBasic();
              table.createPopupMenu();
              frame.setContentPane(table);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              //frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         class PopupListener extends MouseAdapter
              JPopupMenu popup;
              PopupListener(JPopupMenu popupMenu)
                   popup = popupMenu;
              public void mousePressed(MouseEvent e)
                   maybeShowPopup(e);
              public void mouseReleased(MouseEvent e)
                   maybeShowPopup(e);
              private void maybeShowPopup(MouseEvent e)
                   if (e.isPopupTrigger())
                        popup.show(e.getComponent(), e.getX(), e.getY());
    ///when integrate the previous table into here, popup menu won't work
    import java.awt.*;
    import javax.swing.*;
    public class InternalFrameBasic
         extends JFrame
         //implements ActionListener
         private JDesktopPane desktop;
         private JInternalFrame menuWindow;
         public static final int desktopWidth = 800;
         public static final int desktopHeight = 700;
         public InternalFrameBasic(String title)
              super(title);
              //Set up the GUI.
              desktop = new JDesktopPane();
              desktop.putClientProperty("JDesktopPane.dragMode", "outline");
              //Because we use pack, it's not enough to call setSize.
              //We must set the desktop's preferred size.
              desktop.setPreferredSize(new Dimension(desktopWidth, desktopHeight));
              setContentPane(desktop);
              createMenuWindow();
              desktop.add(menuWindow); //DON'T FORGET THIS!!!
              Dimension displaySize = menuWindow.getSize();
              menuWindow.setSize(desktopWidth, displaySize.height);
         private void createMenuWindow()
              menuWindow =
                             new JInternalFrame("Event Watcher", true, //resizable
                                                                                                   true, //closable
                                                                                                   false, //not maximizable
                                                                                                   true); //iconifiable
              menuWindow.setContentPane(new TableBasic());
              menuWindow.pack();
              menuWindow.setVisible(true);
          * Create the GUI and show it.  For thread safety,
          * this method should be invoked from the
          * event-dispatching thread.
         private static void createAndShowGUI()
              //Make sure we have nice window decorations.
              //JFrame.setDefaultLookAndFeelDecorated(true);
              //Create and set up the window.
              JFrame frame = new InternalFrameBasic("Example Internal Frame");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args)
              //Schedule a job for the event-dispatching thread:
              //creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        createAndShowGUI();
    }

    table.createPopupMenu();The above line should not be in the main method. It should be in the constructor class of TableBasic.
    You never execute that method in your InternalFrameBasic class to the mouse listener never gets added to the table.

  • JPopupMenu doesn't work when invoker is not a Swing JComponent ??

    I've written some code that uses a java.awt.Canvas to draw some stuff, and I want to be able to bring up a popup menu over the canvas.
    The problem is that when I try to show the popup menu with my Canvas as the invoker nothing happens: no popup menu appears.
    I also have problems with other AWT components (e.g. with java.awt.TextArea the popup comes up with two clicks but gets hidden behinf the popup that TextArea decides to provide).
    However everything works fine when I use a Swing widget (e.g. JTextArea or JPanel) as the invoker of my popup menu.
    Is this a bug or an undocumented feature?
    The JPopupMenu.show(...) method will happily accept any AWT Component as the invoker. Also the API documentation says nothing on this issue. Also the Swing tutorials doesn't say anything about this.
    I'm tempted to conclude this is an undocumented feature, but that suprises me. Surely I'm not the first person to try and use JPopupMenu with an AWT widget as invoker? Before I file a bug report, can someone tell me if I'm missing something here?
    I have some code to demonstrate this; all you have to do is comment one line and uncomment another to repoduce this behaviour. Let me know if you would like me to post it.

    Quick followup for anyone reading this topic:
    The suggestion of using JPanel and overriding paintComponent(...) is the way to go. I had thought of doing this to begin with, but felt it would be more effort. It's not. It's the same effort as using AWT canvas, but gives better results, and doesn't stuff up JPopupMenu or anything else that wants to interact with a lightweight component.

  • Undo,redo not working properly with JPopupMenu

    if i use JButton for undo ,redo it is working fine. but the same code is not
    working properly if i add it in JPopupMenu.
    what could be the problem.
    thanks

    what could be the problem.Your code is different or written incorrectly and since you didn't post any we can't help.
    [url http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html]How to Use Actions
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Focus on Read-only Text field = accelerators not working

    Pretty much explains the problem.
    In a desktop Application i am developping are different accelerators defined which are working as long as the Editable fields of the frames do have the focus.
    If the Focus is on a read only Field or one of the internal Frames (or somewhere else where you cant type in data) ALL of the given accelerators dont work.
    I just ask this in case of its a known bug (i havent found it as a bug) because since we have our own framework to write swing applications it could also be a bug of that;)
    Thanks for every reply.
    Regards
    Balsi

    Convert the Price text type to number type.it will work.
    check this
    http://sharepoint-works.blogspot.in/2012/05/caml-query-to-get-data-from-sharepoint.html

  • Image in a JPopupMenu

    How to put an image on the left corner of a JPopupMenu like the one in the Windows start menu ?

    Glancing through the API, setBorder looks promising. You'll probably have to write your own Border.

  • Showing visible JPopupMenu in different location does not appear

    In my application if a popup menu is already displayed and the user right clicks to reshow the popup menu in a different location the popup menu disappears. I have included a very simple sample app below that shows the problem.
    Any suggestions as to what I'm doing wrong gratefully received.
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.*;
    public class Test extends JFrame implements MouseListener {
      public static void main(String[] args) {
        Test test = new Test();
        test.setVisible(true);
      JPopupMenu popup;
      public Test() {
        super("Test");
        popup = new JPopupMenu();
        popup.add("Test1");
        popup.add("Test2");
        setSize(400, 300);
        getContentPane().addMouseListener(this);
      public void mouseClicked(MouseEvent e) {
      public void mouseEntered(MouseEvent e) {
      public void mouseExited(MouseEvent e) {
      public void mousePressed(MouseEvent e) {
        popup.show((Component)e.getSource(), e.getX(), e.getY());
      public void mouseReleased(MouseEvent e) {
    }

    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html#popup]How to Use Menus. It shows a better way to check if a popup should be displayed.

  • How to use a GradientPaint as background color in a JPopupMenu

    I want to use a GradientPaint as background color in a JPopupMenu.
    I try to use something like
    GradientPaint p;
    p = new GradientPaint(0, 12, Color.white, 0, 24, Color.pink);
    UIManager.put("MenuItem.selectionBackground", p);but it doesn't work.
    I also tried to extends BasicMenuItemUI in MenuItems
    public class CMenuItem extends JMenuItem {
         public CMenuItem(String text) {
              super(text);
              setUI(BUI.createUI(this));
         static final class BUI extends BasicMenuItemUI {
             private final static BUI ui = new BUI();
             public static BUI createUI(JComponent c) {
                 return ui;
             @Override
             public void update(Graphics g, JComponent c) {
                   if (c.isOpaque()) {
                        Graphics2D g2 = (Graphics2D)g.create();
                        int w = c.getWidth();
                        int h = c.getHeight();
                        GradientPaint p;
                        p = new GradientPaint(0, 12, Color.white, 0, 24, Color.pink);
                        g2.setPaint(p);
                        g2.fillRect(0, 0, w, h);
                        g2.dispose();
                   paint(g, c);
    }I used this technique for JLabel and it works fine.
    Please help

    ok, here the SSCCE. I hope its helpful for an answer.
    import java.awt.Color;
    import java.awt.GradientPaint;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.UIManager;
    import javax.swing.plaf.basic.BasicMenuItemUI;
    public class Menu {
        public JMenuBar createMenuBar() {
             JMenuBar menuBar;
            JMenu menu;
            JMenuItem menuItem;
            //Create the menu bar.
            menuBar = new JMenuBar();
            //Build the first menu.
            menu = new JMenu("A Menu");
            menuBar.add(menu);
             GradientPaint p;
             p = new GradientPaint(0, 12, Color.white, 0, 24, Color.pink);
             UIManager.put("MenuItem.selectionBackground", p);
            menuItem = new JMenuItem("1st item: when selected its background is black: wrong");
            menu.add(menuItem);
             UIManager.put("MenuItem.selectionBackground", Color.pink);
            menuItem = new JMenuItem("2nd item: when selected its background is pink: ok");
            menu.add(menuItem);
            menuItem = new CMenuItem("3rd item: when selected its background is pink: WRONG!");
            menu.add(menuItem);
            return menuBar;
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            Menu demo = new Menu();
            frame.setJMenuBar(demo.createMenuBar());
            //Display the window.
            frame.setSize(450, 260);
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    class CMenuItem extends JMenuItem {
         private static final long serialVersionUID = 1L;
         public CMenuItem(String text) {
              super(text);
              setUI(BUI.createUI(this));
         static final class BUI extends BasicMenuItemUI {
             private final static BUI ui = new BUI();
             public static BUI createUI(JComponent c) {
                 return ui;
             @Override
             public void update(Graphics g, JComponent c) {
                   if (true || c.isOpaque()) {
    //                    System.out.println("update()");
                        Graphics2D g2 = (Graphics2D)g.create();
                        int w = c.getWidth();
                        int h = c.getHeight();
                        GradientPaint p;
                        p = new GradientPaint(0, 0, Color.white, 0, 10, Color.pink);
                        g2.setPaint(p);
                        g2.fillRect(0, 0, w, h);
                        g2.dispose();
                   paint(g, c);
    }Thanks for the help

  • Scroll bar in JPopupMenu when used in JList

    Hi,
    I want variable list (not combo box) where I can add multiple JMenuItems through JPopupMenu. I have created JList in JScrollPane and I have added multiple JMenuItems one by one but in output I am getting the list of JMenuItems without scrollbar. There is no way I can navigate to last JMenuItem in the JList. Could someone help me with integration of JList, JMenuItems, JPopupMenu with scroll bars?
    Below given is the sample code. GUI components have been added through Netbeans.
    public void updatePopUp()
    final JPopupMenu menu = new JPopupMenu();
    menu.setBorder(null);
    menu.setAutoscrolls(true);
    JMenuItem item = new JMenuItem("JMenuItem");
    item.addActionListener(this);
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    menu.setVisible(true);
    menu.pack();
    varList.add(menu);
    // Set the component to show the popup menu
    /* this.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent evt) {
    if (evt.isPopupTrigger()) {
    menu.show(evt.getComponent(), evt.getX(), evt.getY());
    public void mouseReleased(MouseEvent evt) {
    if (evt.isPopupTrigger()) {
    menu.show(evt.getComponent(), evt.getX(), evt.getY());
    }

    I was going to say try setting the preferred (or maximum) size of the scrollpane to force it to be no larger than you want.
    But ...
    a) I don't see you putting menu items in a JList in that code. You are putting them directly into the popup menu (aka, the normal way to do things).
    b) Calling setAutoscrolls() on the JPopupMenu does not make it a "scrollable" menu. It is for supporting dragging of components in a scrollpane (usually). Read the API docs.

Maybe you are looking for

  • How can I use more than 2 dependent dropdown lists

    I would like to create a form using three level of dépendent dropdown lists. Some examples exist with States dropdown list depending on a Country dropdown list. I would like to have a third level City depending on the choice made in the second list.

  • Ideas for a Java based Thesis

    Hi, does anybody have any good ideas for a Java based Thesis project, something that could be completed in no more than 6 months. I have been working with Servlets & J2ME for over a year, but I'm having trouble coming up with a good/challenging proje

  • Loading only last image

    This code is loading the xml correctly, populating the mainClipArray correctly, but only adding the last image to the stage. I think it is not waiting for completeClipLoad() to complete.  I tried removing :void from the function to see if waiting for

  • Problem with Siebel Analyics Web

    Hi, I have installed siebel analytics on my mahine and admintool is working fine and siebel analtyics web is not working. when i type http://localhost/analytics i am not getting the answers page. it is giving me page can not be displayed. when i chec

  • Change Trading Partner

    Hi, How do you change the trading partner in a posted document?  We want to clear an account but there is a problem with the trading partner in one of the line items and we can not change the trading partner as it is greyed out.