user3608233
user3608233

Reputation: 103

Is it possible to open a Jmenu on button click in swing?

Is it possible to open a Jmenu on button click ? I have a button in Jtable and my requirement is that when user presses this button, a Jmenu should appear. So is this possible ?

Upvotes: 0

Views: 1121

Answers (2)

Arijit
Arijit

Reputation: 1674

Do you want to display menuitem on a button click? Then use this code:

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JButton;

public class TestFrame extends JFrame {

    private JPanel contentPane;
    JMenu mnFile;
    JMenuItem mntmExit;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TestFrame frame = new TestFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public TestFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);

        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JButton btnNewButton = new JButton("Click me");
        contentPane.add(btnNewButton, BorderLayout.SOUTH);



        mnFile = new JMenu("file");
        menuBar.add(mnFile);

        mntmExit = new JMenuItem("exit");
        mnFile.add(mntmExit);

        btnNewButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                mnFile.doClick();
            }
        });


    }

}

Upvotes: 0

Ninad Pingale
Ninad Pingale

Reputation: 7069

Yes it is possible. You can by default hide the menus by menu.setVisible(false); method. And on click of button make it menu.setVisible(true);

JFrame frame = new JFrame("List of Metrics used"); 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new ListModelExample()); 
frame.setSize(260, 200); 
frame.setVisible(true);

First thing,these are not necessarily written in main method. And your problem of hiding menu doesn't affect by location of these lines. You can keep it as it is. Also render Jmenu at a required place only, but keep it invisible by default.

Upvotes: 1

Related Questions