Dynamically add menuitem in menu without closing the menu

2.2k Views Asked by At

I want to add JMenuItem without closing JMenu. A menu contains a JTextField, When I press enter in text field, it added a menu Item. My problem is the size of added menu item is too small.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import javax.swing.JTextField;

public class NewJFrame extends javax.swing.JFrame {

public NewJFrame() {
    initComponents();
    this.jMenu1.addSeparator();
    final JTextField jTextField = new JTextField("Menu 1",20);
    this.jMenu1.add(jTextField);   

    jTextField.addActionListener(new ActionListener( ){
        @Override
        public void actionPerformed(ActionEvent e) { 
           final JMenuItem jMenuItem = new JMenuItem(jTextField.getText());
            jMenu1.add(jMenuItem);
             jMenuItem.repaint();
             jMenuItem.revalidate();

        }    
    });

}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {

    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jMenu1.setText("File");
    jMenuBar1.add(jMenu1);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 279, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>//GEN-END:initComponents

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}


// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
// End of variables declaration//GEN-END:variables
}

When I am pressing enter, menu add a menu item, but its width is too small.

How can I fix it?

2

There are 2 best solutions below

0
Gabriel Negut On BEST ANSWER

Instead of repainting it, close the menu and reopen it. Just tried it and it works great, it's as quick as repainting on the spot.

jMenu1.add(jMenuItem);
//jMenuItem.repaint();
//jMenuItem.revalidate();
MenuElement[] selectionPath = MenuSelectionManager.defaultManager().getSelectedPath();
MenuSelectionManager.defaultManager().clearSelectedPath();
MenuSelectionManager.defaultManager().setSelectedPath(selectionPath);
0
DSquare On

You have to update the popupMenu of the jMenu1, calling:

jMenu1.getPopupMenu().pack();

instead of

jMenuItem.repaint();
jMenuItem.revalidate();