1

I am trying to create a JMenuItem that is disabled by default, but a method can be called to enable it. Just for the moment whilst I'm testing out my code, I want the method to be called when I click on another menu item. I have had a look at the documentation for JMenuItem, but I'm pretty new to Java and I'm having trouble finding exactly what I need. I've tried using the updateUI() command, but I that hasn't worked, so I'm totally stuck. Thanks in advance for any help :)

This is what I have so far:

public class initialScreen extends JFrame implements ActionListener{

    Dimension screenSize = new Dimension(800,600);
    JMenuItem runE, newP;

    public initialScreen(){
        super("Experiment Control Suite");
        setSize(screenSize);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JMenuBar bar = new JMenuBar();

        JMenuItem newP = new JMenuItem("New");
        newP.addActionListener(this);

        runE = new JMenuItem("Run");
        runE.setEnabled(false);
        runE.addActionListener(this);

        JMenu exp = new JMenu("Experiment");
        exp.add(runE);      

        JMenu par = new JMenu("Participant");
        par.add(newP);
        bar.add(exp);
        bar.add(par);
        setJMenuBar(bar);

        setVisible(true);
    }

    public void enableRun(){
        runE.setEnabled(true);
        runE.updateUI();
    }

    public void actionPerformed(java.awt.event.ActionEvent e){
        if(e.getSource() == newP) {
            enableRun();  
        }
        else if(e.getSource() == runE) {
            System.out.println("run has been clicked");
        }
    }

}

1 Answer 1

3

Your method enableRun is never invoked because of the following line:

JMenuItem newP = new JMenuItem("New");

Instead, refactor it as such,

newP = new JMenuItem("New");

Now, the field will be correctly initialized and registered as an ActionListener. And thus, when checking the source, enableRun will be invoked and the menu item will be enabled.

Note that in this case, updateUI is completely unnecessary (I suggest you read the javadoc to learn its purpose).

1
  • Aha! Glad it was a silly mistake rather than a fundamental misunderstanding! Thank you :)
    – thisisnic
    Jan 10, 2012 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.