JMenuItem icon prboblem

Hi,
I implemented some JMenuItem in my application. Some of them have icons, some don't. How can I justify their position for those ones without icons??
Currently it's like:
[ ] item1
[ ] itme2
item3
[ ] item4
thanx heaps

Create an empty icon, one that has a size but doesn't paint, and add it to the ones you need justified. That's how I solved the problem for my app.

Similar Messages

  • JMenuItem icon/Text verticle alignment question

    hello,
    can some one help with my question:
    I got 5 JMenuItems in a JMenu, some JMenuItems have icon, some not, I want to align them with icon and text in a neat format, like those in Sun's Forte IDE's Menu:
    but I can only do it like this:
    icon1 open..
    save As..
    icon2 new..
    Exit..
    (above each line represent a JMenuItem, I need to make "save as" ,"Exit" to in line with "open" and "new" in verticle direction,NOT with the icon)
    sb suggest always set an icon for each JMenuItem, set an transparent Icon for alignment those without icons.
    but this sounds not so attractive, are there any other ways? thanks a lot.

    Create a method to do the icons. One can have one parameter (menu text) and the other could have two parameters (icon name, menu text). Have the one with just one parameter set up a default transparent icon.
    Garry.

  • JMenuItem icon, text alignment question

    hello,
    can some one help with my question:
    I got 5 JMenuItems in a JMenu, some JMenuItems have icon, some not, I want to align them with icon and text in a neat format, like those in Sun's Forte IDE's Menu:
    but I can only do it like this:
    icon1 open..
    save As..
    icon2 new..
    Exit..
    (above each line represent a JMenuItem, I need to make "save as" ,"Exit" to in line with "open" and "new" in verticle direction,NOT with the icon)
    sb suggest always set an icon for each JMenuItem, set an transparent Icon for alignment those without icons.
    but this sounds not so attractive, are there any other ways? thanks a lot.

    you can always take a mort drastic action by subclassing MenuItem and
    overriding the painting method.
    But I belive that the first suggestion is faster.

  • JAWS does not always read  Swing menus

    I have come across a problem that involves JAWS 4.51 and Java menus in Internet Explorer.
    I have a Java application that has a JMenuBar. The menu bar contains several JMenus that in turn contain several JMenuItems.
    When navigating through a menu, JAWS reads every JMenuItem. However, once a disabled JMenuItem is reached, JAWS no longer reads the JMenuItems below the disabled one in the open JMenu.
    The problem occurs only in Internet Explorer on "plain" menu items that follow a disabled menu item. The problem does not affect "complex" menu items, such as those that open sub menus.
    I can only reproduce this problem in Internet Explorer 6. Netscape Communicator 7, Web Start clients and a command line launch do not suffer from this problem. Also, JAWS 4.02 is fine as well; only 4.51 has this problem.
    Attached at the end is a sample application that recreates the issue. You'll notice in the sample application that JAWS will not read "A check box menu item" and "Another one" while it will read "A submenu."
    Does anyone have a solution to this? Thanks a lot!
    Sample application:
    ======================================================
    Note: The code below is a modification of the Sun menu tutorial found at http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html
    middle.gif can be downloaded from http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/images/middle.gif
    MenuLookDemoApplet.java:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.ButtonGroup;
    import javax.swing.JMenuBar;
    import javax.swing.KeyStroke;
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JApplet;
    /* MenuLookDemoApplet.java is a 1.4 application that requires images/middle.gif. */
    * This class exists solely to show you what menus look like.
    * It has no menu-related event handling.
    public class MenuLookDemoApplet extends JApplet {
        JTextArea output;
        JScrollPane scrollPane;
        public JMenuBar createMenuBar() {
            JMenuBar menuBar;
            JMenu menu, submenu;
            JMenuItem menuItem;
            JRadioButtonMenuItem rbMenuItem;
            JCheckBoxMenuItem cbMenuItem;
            //Create the menu bar.
            menuBar = new JMenuBar();
            //Build the first menu.
            menu = new JMenu("A Menu");
            menu.setMnemonic(KeyEvent.VK_A);
            menu.getAccessibleContext().setAccessibleDescription(
                    "The only menu in this program that has menu items");
            menuBar.add(menu);
            //a group of JMenuItems
            menuItem = new JMenuItem("A text-only menu item",
                                     KeyEvent.VK_T);
            //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_1, ActionEvent.ALT_MASK));
            menuItem.getAccessibleContext().setAccessibleDescription(
                    "This doesn't really do anything");
            menu.add(menuItem);
            ImageIcon icon = createImageIcon("images/middle.gif");
            menuItem = new JMenuItem("Both text and icon", icon);
            menuItem.setMnemonic(KeyEvent.VK_B);
            menu.add(menuItem);
            menuItem = new JMenuItem(icon);
            menuItem.setMnemonic(KeyEvent.VK_D);
            menu.add(menuItem);
            //a group of radio button menu items
            menu.addSeparator();
            ButtonGroup group = new ButtonGroup();
            rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
            rbMenuItem.setSelected(true);
            rbMenuItem.setMnemonic(KeyEvent.VK_R);
            group.add(rbMenuItem);
            menu.add(rbMenuItem);
            rbMenuItem = new JRadioButtonMenuItem("Another one");
            rbMenuItem.setMnemonic(KeyEvent.VK_O);
            group.add(rbMenuItem);
            menu.add(rbMenuItem);
            rbMenuItem.setEnabled(false);   //@dpb
            //a group of check box menu items
            menu.addSeparator();
            cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
            cbMenuItem.setMnemonic(KeyEvent.VK_C);
            menu.add(cbMenuItem);
            cbMenuItem = new JCheckBoxMenuItem("Another one");
            cbMenuItem.setMnemonic(KeyEvent.VK_H);
            menu.add(cbMenuItem);
            //a submenu
            menu.addSeparator();
            submenu = new JMenu("A submenu");
            submenu.setMnemonic(KeyEvent.VK_S);
            menuItem = new JMenuItem("An item in the submenu");
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_2, ActionEvent.ALT_MASK));
            submenu.add(menuItem);
            menuItem = new JMenuItem("Another item");
            submenu.add(menuItem);
            menu.add(submenu);
            //Build second menu in the menu bar.
            menu = new JMenu("Another Menu");
            menu.setMnemonic(KeyEvent.VK_N);
            menu.getAccessibleContext().setAccessibleDescription(
                    "This menu does nothing");
            menuBar.add(menu);
            return menuBar;
        public Container createContentPane() {
            //Create the content-pane-to-be.
            JPanel contentPane = new JPanel(new BorderLayout());
            contentPane.setOpaque(true);
            //Create a scrolled text area.
            output = new JTextArea(5, 30);
            output.setEditable(false);
            scrollPane = new JScrollPane(output);
            //Add the text area to the content pane.
            contentPane.add(scrollPane, BorderLayout.CENTER);
            return contentPane;
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path) {
            java.net.URL imgURL = MenuLookDemo.class.getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
        public void init() {
            MenuLookDemoApplet demo = new MenuLookDemoApplet();
            setJMenuBar(demo.createMenuBar());
            setContentPane(demo.createContentPane());
    applet.html:
    <html>
    <head>
        <title>Menu Test Page </title>
    </head>
    <body>
    Here's the applet:
    <applet code="MenuLookDemoApplet.class" width="300" height="300">
    </applet>
    </body>
    </html>

    Unfortunately the menu items are fully accessible (or so our internal accessibility tool claims). It doesn't seem to be a problem on that level, but I was hoping that perhaps something else was interfeering.
    As for the JTable reading the previous cell, I've notice that it reads the last non-empty cell (regardless of whether it was the previous cell or not) when clicking or moving with the arrow keys to an empty cell. It works fine when clicking or moving to non-empty cells.
    I don't have any empty cells in the actual application so I did not try to fix it. My suspicions are that either an event is not being fired or the selection position is not being updated on the empty cells.

  • Error with - addStylesToDocument(doc); please help

    Hello, this is my unfinished code for a simple program I am writing. Basically I have a menu and buttons, and am looking to add a JTextPane. I think I have all the code there, except when compiling I am having an error with line addStylesToDocument(doc); if I comment this out then nothing happens but the program runs as normal (before I added the JTextPane code) the error I am getting is "non-static method addStylesToDocument(javax.swing.text.StyledDocument) cannot be referenced from a static context" this makes a little sence to me but not enough to be able to correct it as I am pretty much a beginner...
    If anyone has any suggestions to fix this I would appreciate your input.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class ShoppingCart extends JPanel
                            implements ActionListener {
        protected JButton bapple, borange, bbanana, bstrawberry, blemon, bgrape, b7, b8, b9, b10;
        public JMenuBar createMenuBar() {
         JMenuBar menuBar;
         JMenu menu, submenu;
         JMenuItem menuItem;
         JRadioButtonMenuItem rbMenuItem;
         JCheckBoxMenuItem cbMenuItem;
    menuBar = new JMenuBar();
    menuBar.setBackground(Color.white);
          menu = new JMenu("A Menu");
          menu.setBackground(Color.white);
            menu.setMnemonic(KeyEvent.VK_A);
            menu.getAccessibleContext().setAccessibleDescription(
                    "The only menu in this program that has menu items");
            menuBar.add(menu);
          //a group of JMenuItems
          menuItem = new JMenuItem("A text-only menu item",
                                     KeyEvent.VK_T);
            //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
             menuItem.setBackground(Color.white);
             menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_1, ActionEvent.ALT_MASK));
           menuItem.getAccessibleContext().setAccessibleDescription(
           "This doesn't really do anything");
            menu.add(menuItem);
            ImageIcon icon = createImageIcon("/orange.gif");
            menuItem = new JMenuItem ("Both text and icon", icon);
            menuItem.setMnemonic(KeyEvent.VK_B);
            menuItem.setBackground(Color.white);
          menu.add(menuItem);
          menuItem = new JMenuItem(icon);
          menuItem.setMnemonic(KeyEvent.VK_D);
          menuItem.setBackground(Color.white);
          menu.add(menuItem);
          //a group of radio button menu items
          menu.addSeparator();
          ButtonGroup group = new ButtonGroup();
          rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
          rbMenuItem.setSelected(true);
          rbMenuItem.setMnemonic(KeyEvent.VK_R);
          rbMenuItem.setBackground(Color.white);
          group.add(rbMenuItem);
          menu.add(rbMenuItem);
          //a group if check box menu items
          menu.addSeparator();
          cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
          cbMenuItem.setMnemonic(KeyEvent.VK_C);
          cbMenuItem.setBackground(Color.white);
          menu.add(cbMenuItem);
          cbMenuItem = new JCheckBoxMenuItem("Another one");
          cbMenuItem.setMnemonic(KeyEvent.VK_H);
          cbMenuItem.setBackground(Color.white);
          menu.add(cbMenuItem);
          //a submenu
          menu.addSeparator();
          submenu = new JMenu("A submenu");
          submenu.setBackground(Color.white);
          submenu.setMnemonic(KeyEvent.VK_S);
          menuItem = new JMenuItem("An  item in the submenu");
          menuItem.setAccelerator(KeyStroke.getKeyStroke(
          KeyEvent.VK_2, ActionEvent.ALT_MASK));
          menuItem.setBackground(Color.white);
          submenu.add(menuItem);
          menuItem = new JMenuItem("Another item");
          menuItem.setBackground(Color.white);
          submenu.add(menuItem);
          menu.add(submenu);
          //Build second menu in the menu bar
          menu = new JMenu("Another Menu");
          menu.setBackground(Color.white);
          menu.setMnemonic(KeyEvent.VK_N);
          menu.getAccessibleContext().setAccessibleDescription(
          "This menu does nothing");
          menuBar.add(menu); 
    return menuBar;
        public ShoppingCart() {
            ImageIcon appleButtonIcon = createImageIcon("/apple.gif");
            ImageIcon orangeButtonIcon = createImageIcon("/orange.gif");
            ImageIcon bananaButtonIcon = createImageIcon("/banana.gif");
            ImageIcon strawberryButtonIcon = createImageIcon("/strawberry.gif");
            ImageIcon lemonButtonIcon = createImageIcon("/lemon.gif");
            ImageIcon grapeButtonIcon = createImageIcon("/grape.gif");
            bapple = new JButton(null,  appleButtonIcon);
            bapple.setVerticalTextPosition(AbstractButton.CENTER);
            bapple.setBackground(Color.white);
            bapple.setHorizontalTextPosition(AbstractButton.LEADING);
            bapple.setMnemonic(KeyEvent.VK_D);
            bapple.setActionCommand("apple");
            borange = new JButton(null, orangeButtonIcon);
            borange.setVerticalTextPosition(AbstractButton.BOTTOM);
            borange.setBackground(Color.white);
            borange.setHorizontalTextPosition(AbstractButton.CENTER);
            borange.setMnemonic(KeyEvent.VK_M);
            borange.setActionCommand("orange");
            bbanana = new JButton(null, bananaButtonIcon);
            bbanana.setBackground(Color.white);
            bbanana.setMnemonic(KeyEvent.VK_E);
            bbanana.setActionCommand("banana");
            bstrawberry = new JButton(null,  strawberryButtonIcon);
            bstrawberry.setVerticalTextPosition(AbstractButton.CENTER);
            bstrawberry.setBackground(Color.white);
            bstrawberry.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
            bstrawberry.setActionCommand("strawberry");
            blemon = new JButton(null,  lemonButtonIcon);
            blemon.setBackground(Color.white);
            blemon.setVerticalTextPosition(AbstractButton.CENTER);
            blemon.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
            blemon.setActionCommand("lemon");
            bgrape = new JButton(null,  grapeButtonIcon);
            bgrape.setBackground(Color.white);
            bgrape.setVerticalTextPosition(AbstractButton.CENTER);
            bgrape.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
            bgrape.setActionCommand("grape");
            /*b7 = new JButton(null,  leftButtonIcon);
            b7.setVerticalTextPosition(AbstractButton.CENTER);
            b7.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
            b8 = new JButton(null,  leftButtonIcon);
            b8.setVerticalTextPosition(AbstractButton.CENTER);
            b8.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
            b9 = new JButton(null,  leftButtonIcon);
            b9.setVerticalTextPosition(AbstractButton.CENTER);
            b9.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
            b10 = new JButton(null,  leftButtonIcon);
            b10.setVerticalTextPosition(AbstractButton.CENTER);
            b10.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
            //Listen for actions on buttons
            bapple.addActionListener(this);
            borange.addActionListener(this);
            bbanana.addActionListener(this);
            bstrawberry.addActionListener(this);
            blemon.addActionListener(this);
            bgrape.addActionListener(this);
            bapple.setToolTipText("Apple.");
            borange.setToolTipText("Orange.");
            bbanana.setToolTipText("Banana.");
            bstrawberry.setToolTipText("Strawberry.");
            blemon.setToolTipText("Lemon.");
            bgrape.setToolTipText("Grape.");
           /* b7.setToolTipText("7");
            b8.setToolTipText("8");
            b9.setToolTipText("9");
            b10.setToolTipText("10");
            //Add Components to this container, using the default FlowLayout.
            add(bapple);
            add(borange);
            add(bbanana);
            add(bstrawberry);
            add(blemon);
            add(bgrape);
           /* add(b7);
            add(b8);
            add(b9);
            add(b10);*/
        public void actionPerformed(ActionEvent e) {
            if ("apple".equals(e.getActionCommand())) {
           String  input1 =  JOptionPane.showInputDialog( "How many apples would you like to purchase?" );
            int  number1 = Integer.parseInt( input1 );
             if ("orange".equals(e.getActionCommand())) {
           String  input2 =  JOptionPane.showInputDialog( "How many oranges would you like to purchase?" );
           int  number2 = Integer.parseInt( input2 );
               if ("banana".equals(e.getActionCommand())) {
           String  input3 =  JOptionPane.showInputDialog( "How many bananas would you like to purchase?" );
           int  number3 = Integer.parseInt( input3 );
             if ("strawberry".equals(e.getActionCommand())) {
           String  input4 =  JOptionPane.showInputDialog( "Enter weight of strawberries : " );
           int  number4 = Integer.parseInt( input4 );
             if ("lemon".equals(e.getActionCommand())) {
           String  input5 =  JOptionPane.showInputDialog( "How many lemons would you like to purchase?" );
           int  number5 = Integer.parseInt( input5 );
             if ("grape".equals(e.getActionCommand())) {
           String  input6 =  JOptionPane.showInputDialog( "Enter weight of grapes : " );
           int  number6 = Integer.parseInt( input6 );
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path) {
            java.net.URL imgURL = ShoppingCart.class.getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
    //Create and set up the window.
            JFrame frame = new JFrame("Shopping Cart");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            ShoppingCart newContentPane = new ShoppingCart();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            newContentPane.setBackground(Color.white);
           frame.setJMenuBar(newContentPane.createMenuBar());
            //Display the window.
            frame.pack();
            frame.setVisible(true);
            String[] initString =
            { /* ...  fill array with initial text  ... */ };
            String[] initStyles =
            { /* ...  fill array with names of styles  ... */ };
            JTextPane textPane = new JTextPane();
            StyledDocument doc = textPane.getStyledDocument();
            addStylesToDocument(doc);
            //Load the text pane with styled text.
            try {
            for (int i=0; i < initString.length; i++) {
            doc.insertString(doc.getLength(), initString,
    doc.getStyle(initStyles[i]));
    } catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
    }protected void addStylesToDocument (StyledDocument doc) {
    Style def=new StyleContext ().getStyle (StyleContext.DEFAULT_STYLE);
    Style heading = doc.addStyle ("bold", null);
    StyleConstants.setFontFamily (heading, "SansSerif");
    StyleConstants.setBold (heading, true);
    StyleConstants.setFontSize (heading,30);
    // * The next 3 don't work if that line is commented out
    StyleConstants.setAlignment (heading, StyleConstants.ALIGN_CENTER);
    StyleConstants.setSpaceAbove (heading, 10);
    StyleConstants.setSpaceBelow (heading, 10);
    public static void main() {
    //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();

    CPie wrote:
    o..k.
    I see that you have run out of helpfulness for this session, What the ....? I just told you to add your jtextfield to a jpanel or some other visible component to be seen.
    it is getting late here I will take my business elsewhere tomorrow rather than waiting up for a response which shows you realllly need to find something better to do! And thanks for the help earlier. That was actually useful whereas this wasn't, I'm sure you knew that already,You know that we are all volunteers here. Any time spent here helping you is time away from our friends and families. A little more appreciation is definitely in order or go somewhere else and pay for your help.

  • Accessibilty and JPopupMenu

    I am using JAWS 6 with JDK 1.4.2_06 and Access Bridge 1.2.
    If I add Menuitems to a JMenu which is added to the menubar everything works as expected. One of the menu items is another JMenu, a sub-menu. When JAWS reads this it speaks "submenu" indicating that there is a sub-menu to the right of the current menu item. However, If I attached the exact same menuitems to a JPopupMenu,
    JAWS never speaks "submenu" so the user has no iindication that there is a sub-menu to the right.
    I've taken the attached code from "The JFC Swing Tutorial - Second Edition" and tweaked it slightly so the menubar and popup menu contain the same items.
    It seems as if the accessibility api is expecting the first set of menu items to be attached to a menu parent.
    If worked around this for now by adding another top level menu to the popupmenu to which I add the menuitems.
    Is this a Java or JAWS bug ?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * Like MenuDemo, but with popup menus added.
    public class TextFieldDemo {
    JTextArea output;
    JScrollPane scrollPane;
    String newline = "\n";
    public JMenuBar createMenuBar() {
    JMenuBar menuBar;
    JMenu menu;
    //Create the menu bar.
    menuBar = new JMenuBar();
    //Build the first menu.
    menu = new JMenu("A Menu");
    menu.setMnemonic(KeyEvent.VK_A);
    menu.getAccessibleContext().setAccessibleDescription(
    "The only menu in this program that has menu items");
    JMenuItem[] mi = createAMenu();
    for(int i=0; i < mi.length; ++i)
    menu.add(mi);
    menuBar.add(menu);
    //Build second menu in the menu bar.
    menu = new JMenu("Another Menu");
    menu.setMnemonic(KeyEvent.VK_N);
    menu.getAccessibleContext().setAccessibleDescription(
    "This menu does nothing");
    menuBar.add(menu);
    return menuBar;
    public Container createContentPane() {
    //Create the content-pane-to-be.
    JPanel contentPane = new JPanel(new BorderLayout());
    contentPane.setOpaque(true);
    //Create a scrolled text area.
    output = new JTextArea(5, 30);
    output.setEditable(false);
    scrollPane = new JScrollPane(output);
    //Add the text area to the content pane.
    contentPane.add(scrollPane, BorderLayout.CENTER);
    return contentPane;
    public void createPopupMenu() {
    JMenuItem menuItem;
    //Create the popup menu.
    JPopupMenu popup = new JPopupMenu();
    JMenuItem[] mi = createAMenu();
    for(int i=0; i < mi.length; ++i)
    popup.add(mi[i]);
    //Add listener to the text area so the popup menu can come up.
    MouseListener popupListener = new PopupListener(popup);
    output.addMouseListener(popupListener);
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("TextFieldDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create/set menu bar and content pane.
    TextFieldDemo demo = new TextFieldDemo();
    frame.setJMenuBar(demo.createMenuBar());
    frame.setContentPane(demo.createContentPane());
    //Create and set up the popup menu.
    demo.createPopupMenu();
    //Display the window.
    frame.setSize(450, 260);
    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();
    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());
    private JMenuItem[] createAMenu()
    JMenu submenu;
    JMenuItem menuItem;
    JRadioButtonMenuItem rbMenuItem;
    JCheckBoxMenuItem cbMenuItem;
    JMenuItem items[] = new JMenuItem[8];
    //a group of JMenuItems
    menuItem = new JMenuItem("A text-only menu item",
    KeyEvent.VK_T);
    //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_1, ActionEvent.ALT_MASK));
    menuItem.getAccessibleContext().setAccessibleDescription(
    "This doesn't really do anything");
    items[0]=menuItem;
    menuItem = new JMenuItem("Both text and icon");
    menuItem.setMnemonic(KeyEvent.VK_B);
    items[1]=menuItem;
    menuItem = new JMenuItem("icon only");
    menuItem.setMnemonic(KeyEvent.VK_D);
    items[2]=menuItem;
    //a group of radio button menu items
    ButtonGroup group = new ButtonGroup();
    rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
    rbMenuItem.setSelected(true);
    rbMenuItem.setMnemonic(KeyEvent.VK_R);
    group.add(rbMenuItem);
    items[3]=rbMenuItem;
    rbMenuItem = new JRadioButtonMenuItem("Another one");
    rbMenuItem.setMnemonic(KeyEvent.VK_O);
    group.add(rbMenuItem);
    items[4]=rbMenuItem;
    //a group of check box menu items
    cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
    cbMenuItem.setMnemonic(KeyEvent.VK_C);
    items[5]=cbMenuItem;
    cbMenuItem = new JCheckBoxMenuItem("Another one");
    cbMenuItem.setMnemonic(KeyEvent.VK_H);
    items[6]=cbMenuItem;
    //a submenu
    submenu = new JMenu("A submenu");
    submenu.setMnemonic(KeyEvent.VK_S);
    menuItem = new JMenuItem("An item in the submenu");
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_2, ActionEvent.ALT_MASK));
    submenu.add(menuItem);
    menuItem = new JMenuItem("Another item");
    submenu.add(menuItem);
    items[7]=submenu;
    return(items);

    Hi;
    I want to add chekboxes to a poupup menu ,how can I do that. I already have a submenu with names of columns ton hide and show them using chekcboxes and i want that same menu as a popup when i click in the tableheader.
    thanx

  • Jmenu setAccessibleDescription

    Anyone know about below this line, how its work
    menu.getAccessibleContext().setAccessibleDescription(
    "This menu does nothing");
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.ButtonGroup;
    import javax.swing.JMenuBar;
    import javax.swing.KeyStroke;
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    /* MenuLookDemo.java is a 1.4 application that requires images/middle.gif. */
    * This class exists solely to show you what menus look like.
    * It has no menu-related event handling.
    public class MenuLookDemo {
        JTextArea output;
        JScrollPane scrollPane;
        public JMenuBar createMenuBar() {
            JMenuBar menuBar;
            JMenu menu, submenu;
            JMenuItem menuItem;
            JRadioButtonMenuItem rbMenuItem;
            JCheckBoxMenuItem cbMenuItem;
            //Create the menu bar.
            menuBar = new JMenuBar();
            //Build the first menu.
            menu = new JMenu("A Menu");
            menu.setMnemonic(KeyEvent.VK_A);
            menu.getAccessibleContext().setAccessibleDescription(
                    "The only menu in this program that has menu items");
            menuBar.add(menu);
            //a group of JMenuItems
            menuItem = new JMenuItem("A text-only menu item",
                                     KeyEvent.VK_T);
            //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_1, ActionEvent.ALT_MASK));
            menuItem.getAccessibleContext().setAccessibleDescription(
                    "This doesn't really do anything");
            menu.add(menuItem);
            ImageIcon icon = createImageIcon("images/middle.gif");
            menuItem = new JMenuItem("Both text and icon", icon);
            menuItem.setMnemonic(KeyEvent.VK_B);
            menu.add(menuItem);
            menuItem = new JMenuItem(icon);
            menuItem.setMnemonic(KeyEvent.VK_D);
            menu.add(menuItem);
            //a group of radio button menu items
            menu.addSeparator();
            ButtonGroup group = new ButtonGroup();
            rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
            rbMenuItem.setSelected(true);
            rbMenuItem.setMnemonic(KeyEvent.VK_R);
            group.add(rbMenuItem);
            menu.add(rbMenuItem);
            rbMenuItem = new JRadioButtonMenuItem("Another one");
            rbMenuItem.setMnemonic(KeyEvent.VK_O);
            group.add(rbMenuItem);
            menu.add(rbMenuItem);
            //a group of check box menu items
            menu.addSeparator();
            cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
            cbMenuItem.setMnemonic(KeyEvent.VK_C);
            menu.add(cbMenuItem);
            cbMenuItem = new JCheckBoxMenuItem("Another one");
            cbMenuItem.setMnemonic(KeyEvent.VK_H);
            menu.add(cbMenuItem);
            //a submenu
            menu.addSeparator();
            submenu = new JMenu("A submenu");
            submenu.setMnemonic(KeyEvent.VK_S);
            menuItem = new JMenuItem("An item in the submenu");
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_2, ActionEvent.ALT_MASK));
            submenu.add(menuItem);
            menuItem = new JMenuItem("Another item");
            submenu.add(menuItem);
            menu.add(submenu);
            //Build second menu in the menu bar.
            menu = new JMenu("Another Menu");
            menu.setMnemonic(KeyEvent.VK_N);
           menu.getAccessibleContext().setAccessibleDescription(
                    "This menu does nothing");
          menuBar.add(menu);
            return menuBar;
        public Container createContentPane() {
            //Create the content-pane-to-be.
            JPanel contentPane = new JPanel(new BorderLayout());
            contentPane.setOpaque(true);
            //Create a scrolled text area.
            output = new JTextArea(5, 30);
            output.setEditable(false);
            scrollPane = new JScrollPane(output);
            //Add the text area to the content pane.
            contentPane.add(scrollPane, BorderLayout.CENTER);
            return contentPane;
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path) {
            java.net.URL imgURL = MenuLookDemo.class.getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
         * 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 JFrame("MenuLookDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            MenuLookDemo demo = new MenuLookDemo();
            frame.setJMenuBar(demo.createMenuBar());
            frame.setContentPane(demo.createContentPane());
            //Display the window.
            frame.setSize(450, 260);
            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();
    }

    Quit cross-posting: http://forum.java.sun.com/thread.jspa?threadID=705896
    Two of us have now had to waste time asking you to clarify your poorly worded question. Thats why you keep the posting in the relevant forum so all relevant questions and answers are in one place.

  • Setting icon for the JMenuItem

    I am trying to set the Icon for the JMenuItem and not able to do so.
    I have the Images directory in the classes which has all the images. Is this the way to give the dir path. When do I give '\' and when do I give '/' or'//' or'\\'? Thanks.
    I gave
    JMenuItem mnuitmFileNew = new JMenuItem(new ImageIcon("Images//new.jpg"));
    and later in Jbinit() method I have this.
    mnuitmFileNew.setMnemonic('N');
    mnuitmFileNew.setText("New");
    mnuitmFileNew.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    mnuitmFileNew_actionPerformed(e);
    });

    Hi,
    I'm not sure if you've seen this yet:
    http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html
    If you still have any questions please post again.
    Regards,
    Matt
    Java Developer Technical Support
    Sun Microsystems

  • Icons in JMenuItem

    I want to have icons on my menu. I am using the Windows look and feel.
    On most native windows menus the icons appear in a separate column on the left. When I use icons in java menus they appear much too far to the right and the text doesn't align properly with the icons unless I move the text using Insets. There has to be a better way that gets the icons further left and the text aligned. Here is my code...
         private void createMenuItem(String text, int mnemon,
                                       KeyStroke accel, JMenu owner, Icon ic)
              JMenuItem temp=null;
              if (ic == null)
                   temp = new JMenuItem(text,mnemon);
                   Insets in = temp.getInsets();               
                   in.left += 20;//icon width is 20
                    temp.setMargin(in);
              else
                   temp = new JMenuItem();
                    temp.setHorizontalTextPosition(SwingConstants.RIGHT);
                    temp.setText(text);
                    temp.setMnemonic(mnemon);
                    temp.setIcon(ic);
              if (accel != null)
              temp.setAccelerator(accel);
              temp.addActionListener(this);
              if (ic != null) temp.setIcon(ic);
              owner.add(temp);
         }

    I have had this problem too. The misaligned text looks terrible.
    Here is the solution I found, using an EmptyIcon class :
    http://www.javapractices.com/Topic169.cjp
    There is an example Swing app implementation on the same site which uses this technique. You may browse the javadoc, which has links to source code :
    http://www.javapractices.com/Topic170.cjp
    Example of a class in the example app which uses this technique :
    http://www.javapractices.com/apps/stocksmonitor/javadoc/stocksmonitor/ui/EditUserPreferencesAction.html
    Clicking on a class or method name will link to the source code....
    - John

  • Image Icon in JMenuItem

    I am building a JMenu, using JMenuItem, I want to show a Icon "V" in JMenuItem, so the user can click on it to see more options, just like we get in windows 2000 , in your start menu. where it only shows the menus which we have recently accessed, and hide others.
    Is there any standard java class for it or i will have to download a image and create a Icon from it and use it in JMenuItem.
    I dont know if any of the Implementing Classes of Interface Icon can be used for it

    If u want a icon then there is a consturctor available which takes in a Icon.
    JMenuItem( String, Icon )
    but if u want just to underline V then u can set the accelerator using setAccelerator method.
    menuItem.setAccelerator( KeyStroke.getKeyStroke(
              KeyEvent.VK_F, Event.CTRL_MASK ) );
    here it is set for cntrl + F
    Hope this would help
    Nagaraj

  • Own definition of Icon for JMenuItem

    Every time I try to add ColorIcon to JMenuItem it eats name space. How can I separate name from icon?
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Toolkit;
    import javax.swing.AbstractAction;
    import javax.swing.Icon;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    public class Test extends JFrame {
         public Test() {
              JMenuBar menu = new JMenuBar();
              JMenu mFile = new JMenu("File");
              menu.add(mFile);
              JMenu mColor = new JMenu("Color");
              mFile.add(mColor);
              mColor.add(new TakeAction(Color.RED, "This is red"));
              setJMenuBar(menu);
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              setPreferredSize(new Dimension(screenSize.width/2, screenSize.height/2));
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              pack();
              setLocationRelativeTo(null);
              setVisible(true);
         public static void main(String[] args) {
              new Test();
         public class TakeAction extends AbstractAction implements ActionListener{
              public TakeAction (Color color, String name) {
                   super(name);
                   putValue(SMALL_ICON, new ColorIcon(color));
              @Override
              public void actionPerformed(ActionEvent e) {
         public class ColorIcon implements Icon {
             private int width = 15;
             private int height = 15;
             private Color color;
             public ColorIcon(Color color) {
                  this.color = color;
              @Override
              public int getIconHeight() {
                   return 0;
              @Override
              public int getIconWidth() {
                   return 0;
              @Override
              public void paintIcon(Component c, Graphics g, int x, int y) {
                   Graphics2D g2d = (Graphics2D) g.create();
                      g2d.setColor(color);
                      g2d.fillOval(3, 3, width-3, height-3);
                          g2d.dispose();
    }Edited by: Giraphant on Dec 30, 2010 3:23 AM
    Edited by: Giraphant on Dec 30, 2010 3:24 AM

    private int width = 15;
    private int height = 15;
    @Override
    public int getIconHeight() {
      return 0;
    @Override
    public int getIconWidth() {
      return 0;
    }Does this make sense to you?

  • JMenuItem with icon

    I'm working on a project that has so emulate a 16 bit RISC microprocessor. And I decided to build an Applet and I created a menu for the applet. The problem is that I can't add icons to the menu items. I tried to add icons for a menu in a frame (stand-alone) application and it worked. But I can't in the applet.
    I tried using the following code:
    ImageIcon icon= new ImageIcon("icon.gif");
    menuitem.setIcon(icon);
    And it doesn't work!! :-(
    Why? Or you can't use icons in applet menus?

    Let's assume you have the icon in the same directory
    as the html file the applet's in on the server:
    new ImageIcon(new URL(getDocumentBase(), "icon.gif"));
    I think just the string argument has to be a file.Thanks a lot! I should have tried that... but I forgot that I had to work with images in an applet. That works..

  • Disabled JMenuItem doesn show animated gif

    Hi there
    I would like to have a popup menu with actions that are enabled after they have finished with some background task taking some time. Basically this works fine for the enabling action on a shown popup. However, adding an animated gif as the icon or disabled icon does not show it in disabled state. In enabled state it works perfect. Please have a try with the sample code. You should see the disabled item for 2 secs and the icon is not showing up. After being enabled, it does. Invoking the menu again shows the animated gif in its last state left, but not moving any more.
    I guess, repaints are not done appropriately in disabled state... Any ideas how to solve that would be highly appreciated :-)
    Actually I used the icon at http://mentalized.net/activity-indicators/indicators/pascal_germroth/indicator.white.gif
    Cheers
    Daniel
    public class Main
      public static void main(String[] args)
        final JFrame frame = new JFrame();
        frame.addMouseListener(new MouseAdapter()
          public void mousePressed(final MouseEvent e)
            final JPopupMenu popup = new JPopupMenu();
            popup.add(new JMenuItem("Open..."));
            popup.add(new JMenuItem("Close"));
            final JMenuItem action = new JMenuItem("Long loading until enabled");
            action.setIcon(new ImageIcon("C:/spinner.gif"));
            action.setDisabledIcon(new ImageIcon("C:/spinner.gif"));
            popup.add(action).setEnabled(false);
            popup.show(e.getComponent(), e.getX(), e.getY());
            SwingUtilities.invokeLater(new Runnable()
              public void run()
                try
                  Thread.sleep(2000);
                  action.setEnabled(true);
                catch (InterruptedException e1)
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }Edited by: daniel.frey on Apr 22, 2009 7:50 AM

    The problem is that you are causing the EDT to sleep, which means the GUI can't repaint itself. Read the section from the Swing tutorial on Concurrency to understand what is happening.

  • JMenuItem.

    Dear all,
    I downloaded the following program from Sun to create JMenuBar and JManuItem but there is no function. I need to display say 'Hello World' when I click one of the JMenuItem. May I know how to write the function in the following context ?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.ButtonGroup;
    import javax.swing.JMenuBar;
    import javax.swing.KeyStroke;
    import javax.swing.ImageIcon;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    * This class exists solely to show you what menus look like.
    * It has no menu-related event handling.
    public class MenuLookDemo extends JFrame {
        JTextArea output;
        JScrollPane scrollPane;
        public MenuLookDemo() {
            JMenuBar menuBar;
            JMenu menu, submenu;
            JMenuItem menuItem;
            JCheckBoxMenuItem cbMenuItem;
            JRadioButtonMenuItem rbMenuItem;
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            //Add regular components to the window, using the default BorderLayout.
            Container contentPane = getContentPane();
            output = new JTextArea(5, 30);
            output.setEditable(false);
            scrollPane = new JScrollPane(output);
            contentPane.add(scrollPane, BorderLayout.CENTER);
            //Create the menu bar.
            menuBar = new JMenuBar();
            setJMenuBar(menuBar);
            //Build the first menu.
            menu = new JMenu("A Menu");
            menu.setMnemonic(KeyEvent.VK_A);
            menu.getAccessibleContext().setAccessibleDescription(
                    "The only menu in this program that has menu items");
            menuBar.add(menu);
            //a group of JMenuItems
            menuItem = new JMenuItem("A text-only menu item",
                                     KeyEvent.VK_T);
            //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_1, ActionEvent.ALT_MASK));
            menuItem.getAccessibleContext().setAccessibleDescription(
                    "This doesn't really do anything");
            menu.add(menuItem);
            menuItem = new JMenuItem("Both text and icon",
                                     new ImageIcon("images/middle.gif"));
            menuItem.setMnemonic(KeyEvent.VK_B);
            menu.add(menuItem);
            menuItem = new JMenuItem(new ImageIcon("images/middle.gif"));
            menuItem.setMnemonic(KeyEvent.VK_D);
            menu.add(menuItem);
            //a group of radio button menu items
            menu.addSeparator();
            ButtonGroup group = new ButtonGroup();
            rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
            rbMenuItem.setSelected(true);
            rbMenuItem.setMnemonic(KeyEvent.VK_R);
            group.add(rbMenuItem);
            menu.add(rbMenuItem);
            rbMenuItem = new JRadioButtonMenuItem("Another one");
            rbMenuItem.setMnemonic(KeyEvent.VK_O);
            group.add(rbMenuItem);
            menu.add(rbMenuItem);
            //a group of check box menu items
            menu.addSeparator();
            cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
            cbMenuItem.setMnemonic(KeyEvent.VK_C);
            menu.add(cbMenuItem);
            cbMenuItem = new JCheckBoxMenuItem("Another one");
            cbMenuItem.setMnemonic(KeyEvent.VK_H);
            menu.add(cbMenuItem);
            //a submenu
            menu.addSeparator();
            submenu = new JMenu("A submenu");
            submenu.setMnemonic(KeyEvent.VK_S);
            menuItem = new JMenuItem("An item in the submenu");
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_2, ActionEvent.ALT_MASK));
            submenu.add(menuItem);
            menuItem = new JMenuItem("Another item");
            submenu.add(menuItem);
            menu.add(submenu);
            //Build second menu in the menu bar.
            menu = new JMenu("Another Menu");
            menu.setMnemonic(KeyEvent.VK_N);
            menu.getAccessibleContext().setAccessibleDescription(
                    "This menu does nothing");
            menuBar.add(menu);
        public static void main(String[] args) {
            MenuLookDemo window = new MenuLookDemo();
            window.setTitle("MenuLookDemo");
            window.setSize(450, 260);
            window.setVisible(true);
    }

    In the same tutorial there is a section titled "Handling Events From Menu Items" which includes sample code:
    http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html#event

  • How to set Icon on MenuItem

    How to set icon on MenuItem, but not in JMenuItem?

    saleemtol003 wrote:
    You are right.It's not possible to set icon on menuItem.
    I am talking about SystemTray in which I added PopupMenu with MenuItem.
    but I need MenuItem with icon.Is there another way to solve this problem?Nope, just because you're adding a PopupMenu to a TrayIcon does not change the fact that MenuItems cannot have icons.

Maybe you are looking for

  • Can't launch Photoshop CS5 after upgrading to Mountain Lion

    Reinstalling didn't help.  It crashes during the intializing phase, and I'm left with an error report.  Can anyone make any sense of it? Process:         Adobe Photoshop CS5 [2681] Path:            /Applications/Adobe Photoshop CS5/Adobe Photoshop CS

  • Best practice for upgrading an old system?

    My Archlinux installation seems to have been upgraded over three years ago for the last time. Today, a naive pacman -Syu resulted in a number of file conflict errors and wasn't carried out. I then checked the list of announcements since 2011 and iden

  • Journal data --- for multiple interfaces

    hi, i have a source table. i want to capture the journal data on this table.And use the data stored in the "jv$ tables" in multiple interfaces. The multiple interfaces have same source table and are linked in a package. Is it possible to achive it.

  • Where does the execution of the code begin

    Hi all, I am wondering where the execution of the code below begin. Declare cursor c_zip(p_state in zipcode.state%type) is select zip, city , state from zipcode where state=p_state begin for r_zip in c_zip('NJ') loop dbms_output.put_line(r_zip.city||

  • Mavervick OSx with font smoothing error. Crashes Photoshop

    I keep getting the error message "For the Photoshop UI to display correctly, open System Preferences, click Appearance, and turn off text smoothing for font sizes 8 and smaller." I go into preferences and into general but there is no setting to turn