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");
}
}
}
Your method
enableRunis never invoked because of the following line:Instead, refactor it as such,
Now, the field will be correctly initialized and registered as an
ActionListener. And thus, when checking the source,enableRunwill be invoked and the menu item will be enabled.Note that in this case,
updateUIis completely unnecessary (I suggest you read the javadoc to learn its purpose).