JMenu,JMenuItems and JRadioButtonMenuItem

Hi I have a JMenu in the JMenuBar.I have a JMenu in it and Then I have 6 JMenuItems which are Of the JRadioButtonMenuItems.
I need to get on of it selected manually .Can somebody help me in this.I am able to get the name if the MenuItems but I am not able to get it selected.
Thanks in advance.

Read this section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html]Using Menus for an example.

Similar Messages

  • JMenuItem and JTextField doesn't look right after upgrading to Java 8

    I just upgraded to JDK 8u25
    I have a legacy Swing application, which makes use of JMenuItem and JTextField
    I realize, after upgrading, there is a bolder grey vertical border at the left side of JMenuItem and JTextField
    JMenuItem
    JTextField
    This only happen, if I were using look n feel com.sun.java.swing.plaf.windows.WindowsLookAndFeel
    Before that, I never have such problem. Anyone know is there any workaround for such problem?
    Here's the code example to demonstrate the problem.
    package javaapplication5;
    * @author yccheok
    public class NewJFrame extends javax.swing.JFrame {
         * Creates new form NewJFrame
        public NewJFrame() {
            initComponents();
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            jTextField1 = new javax.swing.JTextField();
            jMenuBar1 = new javax.swing.JMenuBar();
            jMenu1 = new javax.swing.JMenu();
            jMenu2 = new javax.swing.JMenu();
            jMenuItem1 = new javax.swing.JMenuItem();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jMenu1.setText("File");
            jMenuBar1.add(jMenu1);
            jMenu2.setText("Edit");
            jMenuItem1.setText("jMenuItem1");
            jMenu2.add(jMenuItem1);
            jMenuBar1.add(jMenu2);
            setJMenuBar(jMenuBar1);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(21, 21, 21)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(232, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(19, 19, 19)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(230, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
         * @param args the command line arguments
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Windows".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            //</editor-fold>
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JMenu jMenu1;
        private javax.swing.JMenu jMenu2;
        private javax.swing.JMenuBar jMenuBar1;
        private javax.swing.JMenuItem jMenuItem1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration                  
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            //</editor-fold>
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JMenu jMenu1;
        private javax.swing.JMenu jMenu2;
        private javax.swing.JMenuBar jMenuBar1;
        private javax.swing.JMenuItem jMenuItem1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration                  

    The site looks OK -- actually quite impressive for what appears to be a from-scratch design.
    In Opera 10 under Snow Leopard 10.6.1, the design doesn't start to explode until the horizontally scrolling marquee comes across. I would strongly recommend just removing that marquee; it is an extremely outdated element of web design. If you do that, the design shouldn't blow up on you in other browsers.

  • JMenu/JMenuItem background color error.

    Hi,
    I have coded using Mouse Listener to highlight the JMenu/JMenuItem if mouse is brought over it.
    It works fine using the entered and exited properties.
    But here is were the issue crops up � if I click on a JMenuItem and keeping it pressed, drag the mouse out of the JMenuItem area then the highlighted color for the selection scenario remains even if I bring the mouse back into the JMEnuItem�s area or for that matter even if I move it over other JMenuItems, the particular menu item over which mouse is of course highlighted but the originally selected JMenuItem (from which I dragged out and released the mouse) constantly appears highlighted.
    This issue was faced only on AIX running with JDK 1.3
    please advise on a solution.

    I made that change to my code. It isn't throwing the error anymore, but it's also not working at all now.
    The field is now defaulted red, and it has a static value of 255 - it's not changing the value when I enter numbers into the other fields like it should.
    Here is my code now:
    //Subtract items to get the value of the field
    this.rawValue = Num.rawValue - (Sub.rawValue);
    if (this.rawValue < 0) {
        this.fillColor = ("231","179","173"); //Set the color to red if value is less than zero
    else {
        this.fillColor = ("255","255","255"); //Set the color back to white if value is zero or greater
    If I change it to this format: this.fillColor = ("231,179,173"); then the field starts working again, but it also throws the error again.
    It's so weird. It's like the program doesn't know that fillColor is supposed to have three values?

  • JMenuItem and JPanel issues!

    I have a JMenuBar set up for my program and I want each JMenuItem to show a seperate JPanel when clicked. I've tried container.add(panel1); and panel1.setVisible(true); // (Previously set to false) but neither work.
    This is how I've implemented it:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class LibraryGUI extends JFrame {
         private Container container;
         private JPanel addStaffPanel, addStudentPanel;
         private JLabel addStaffTitle, addStudentTitle;
         // Set up GUI
         public LibraryGUI() {
              super("Visual Library 2.0");
              container = getContentPane();
              // Main menu items
              JMenu fileMenu = new JMenu("File");
              JMenu addMenu = new JMenu("Add");
              JMenu removeMenu = new JMenu("Remove");
              JMenu displayMenu = new JMenu("Display");
              // Set up 'File' menu items
              JMenuItem exit = new JMenuItem("Exit");
              // Set up 'Add' menu items
              JMenuItem addStaff = new JMenuItem("Add Staff Member");
              JMenuItem addStudent = new JMenuItem("Add Student Member");
              // Set up the 'File' menu
              fileMenu.add(exit);
              // Set up the 'Add' menu
              addMenu.add(addStaff);
              addMenu.add(addStudent);
              // Create menu bar and attach it to the window
              JMenuBar bar = new JMenuBar();
              setJMenuBar(bar);
              // Add menu's to the menu bar
              bar.add(fileMenu);
              bar.add(addMenu);
              // File --> Exit (THIS WORKS FINE!)
              exit.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        System.exit(0);
              // Set up 'Add Staff Member' title
              addStaffTitle = new JLabel();
              addStaffTitle.setText("Add Staff Member");
              // Set up 'Add Student Member' title
              addStudentTitle = new JLabel();
              addStudentTitle.setText("Add Student Member");
              // Set up 'Add Staff Member' panel
              addStaffPanel = new JPanel();
              addStaffPanel.setLayout(new GridLayout(1,1));
              addStaffPanel.add(addStaffTitle);
              // Add --> Add Staff Member (THIS DOESN'T WORK)
              addStaff.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        container.add(addStaffPanel);
              // Set up 'Add Student Member' panel
              addStudentPanel = new JPanel();
              addStudentPanel.setLayout(new GridLayout(1,1));
              addStudentPanel.add(addStudentTitle);
              // Window settings
              container.setBackground(Color.WHITE);
              setSize(600, 400);
              setVisible(true);
         public static void main(String args[]) {
              LibraryGUI application = new LibraryGUI();
              application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }It compiles fine, no errors. But when the menu items are clicked it just does nothing. Any ideas?
    - Will

    Hmm, normally after adding/remove component to/from a panel you would need to use panel.revalidate. However, this didn't seem to work. Playing around I came up with the following:
    container.setVisible(false);
    container.removeAll();
    container.add(addStudentPanel);
    container.setVisible(true);
    However, instead of using this approach I suggest you look at using a CardLayout. This Layout Manager was designed for this situation, to replace the entire contents of a panel with multiple different panels. Read this section from the Swing tutorial on Using Layout Managers:
    http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html
    An added bonus when using the CardLayout is that you can share the same ActionListeners for all panels. When adding a panel to the CardLayout you need to give a name to the panel (eg. "staff", "student"). When you create your menu items you can use the setActionCommand(...) method:
    addStaff.setActionCommand("staff");
    addStudend.setActionCommand("student");
    Now in your action listener you would just use the event.getActionCommand() method to determine which card panel to display.

  • 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

  • JMenuItem and MouseListener

    Hi there!!
    I'm working with nested menus.
    Anyone knows if a JMenuItem doesn't catch mouseClicked() event when it belongs to a nested menu?
    I can work with mousePressed() and mouseReleased() as a "mouse click", but i'd like to know the answer to it.
    Regards, eyitikawa

    S. pschugg, thanks for the reply.
    I was using ActionListeners too.
    But I need a effect of "on mouse over" a JMenuItem change its style and "on mouse out" the same returns to its original state. That's why I changed to MouseListener.
    Does anyone ever needed this kind of effect?
    Regards, eyitkawa.

  • JMenuItem and JPopupMenu

    Is there an esay why round this issue?
    I've got a JMenuItem that I would like to add to MULTIPLE menu's.
    when I add the JMenuItem to a "new" JPopup it dissappears from the previous one.
    eg
    JPopupMenu menu1 = new JPopupMenu();
    JPopupMenu menu2 = new JPopupMenu();
    JMenuItem disappearingItem = new JMenuItem("I'll only appear once");
    menu1.add(disappearingItem);
    menu2.add(disappearingItem);I know I could "just" create a new JMenuItem that is the same, but this seems like a hassle. Why can't I have the same JMenuItem appearing in different menus?
    Thanks,
    Steve

    Hello,
    I think its to avoid incosistency.
    This is the responsible source-code from java.awt.Container:
    /* Reparent the component and tidy up the tree's state. */
             if (comp.parent != null) {
              comp.parent.remove(comp);
                        if (index > ncomponents) {
                            throw new IllegalArgumentException("illegal component position");
                }Ragards,
    Tim

  • JMenuItem and MouseListener Problems

    I add the MouseListener to the JMenu, the event works.
    but when I add the MouseListener to the JMenuItem, it didn't work?
    why?
    the following is my code:                         jMenuItemRelogin = new JMenuItem();
                             jMenuLogin.add(jMenuItemRelogin);
                             jMenuItemRelogin.setText("Relogin");
                             jMenuItemRelogin.addMouseListener(new MouseAdapter(){
                                  public void mouseClicked(MouseEvent evt){
                                       reloginMouseClicked(evt);
                             });

    You don't use MouseListeners. You use ActionListeners.
    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html]How to Use Menus for working examples.

  • JMenu text and strange characters

    Hello,
    Using jdk1.4.1, Win2K pro, and setting the L&F to windows causes strange characters to appear in my JMenu text. Using either:
    JMenu new = new JMenu("Create/Modify a file");
    or
    new.setText("Create/Modify a file")will cause this "Create/Modify. a file"
    So I end up with periods or comas all through my file menus.
    Anyone else expierenced this with 1.4.1?
    Didn't happen in 1.3.1
    Thanks
    Jim

    There are different solution already posted in the forum. This is one of them:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=303795

  • AbstractAction and JRadioButtonMenuItem

    I can use the Action putValue(...) method to set the text, icon, mneumonic, accel., etc for my JRadioButtonMenuItem. I can also call setEnabled(...).
    Is there a way to use Action to control the state (selected or not-selected) of a JRadioButton or JRadioButtonMenuItem?

    No, Action doesn't support a "selected" property yet (it will be added, along with a "large-icon" property, in the 1.5 release). In the meantime, the source code for this article contains a workaround you might be able to use.

  • Showing multiple popups

    Hey all,
    I am trying to implement my own menu system by subclassing JMenu, JMenuItem, and JPopupMenu. Everything works fine, except for one glitch: when what should be a submenu opens, the main menu closes because they are both popups and swing only allows one popup to display at a time. Looking through the source I can't see how JMenu gets around this. Can anyone offer a suggestion?
    I see JPopupMenu.isSubPopupMenu(), but that is package private and, as far as I can tell completely unused. I also see PopupMenu.setInvoker() but that does not have the desired effect.
    Thanks!
    bjorn

    user12952952 wrote:
    Hey all,
    I am trying to implement my own menu system by subclassing JMenu, JMenuItem, and JPopupMenu.Why? That is, what behavior are you changing that merits subclassing?
    There may be a solution for your requirements that doesn't involve subclassing.
    db

  • 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'.

  • Error in JComboBox and JMenu with JDK 1.6

    We have a Desktop application that uses JMenuBar, JMenu, and JMenuItem and JComboBox. As we use the application, is the disappearance of the menu items, ie, they are not painted and does not drop down.
    We tested with jdk1.6.0 update 17.
    We tested with jdk1.6.0 update 22.
    We tried to force the paint component among other ways to make it work, but without success!
    We would like to know if it's a bug in Swing because we know other applications that use implementations Desktop also the same problem occurs.
    We look back!
    Edited by: Rubens on May 13, 2012 10:16 PM

    Works for me. The updates you tried are rather old too. But I would first suspect your code. Adding menu items fom the wrong thread for example.

  • JMenu and making the popup always visible

    hi,
    i need to keep the menu's popup visible always and eventually the selection of an item even when the focus moves to another component-a text field nearby for example.can this (and how if it is) be achieved or it is totally up to the look and feel and i can't do much about it?
    thank you.

    just for the record,it seems it actually is doable.at least i have a prototype working.it involves removing default mouse listeners from jmenu i jmenuitem and installing "custom" ones that manage the transition of the menu from one state to another.

  • Jpopupmenu, jmenuitem, jmenu... transparent

    I have extended JPopupmenu, JMenuItem, and JMenu in order to obtain some behaivier (transparent menus). Im having this prob. that the JMenu creates a normal JPopupMenu, where I would like it to use my extended JPopupMenu. I thought about overriding the method in JMenu which creates the JPopupMenu, but the JPop is private in jmenu. How to do this? I could ofcourse copy all the code of the jmenu class and just change the creation of the jpopupmenu, but that is probably illegal or something. Any ideas?
    Stig.

    I have the same problem.
    I run my code in jdk1.3 and it works great. But in 1.4, the transparency is gone, and depeneding on the implementation, the repainting sometimes gets real crazy.

Maybe you are looking for